在Python中-解析响应xml并查找特定的文本值 [英] In Python - Parsing a response xml and finding a specific text vaule

查看:478
本文介绍了在Python中-解析响应xml并查找特定的文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我在使用xml和python时特别困难.我遇到的情况是这种情况,我试图计算一个单词在xml文档中出现的次数.很简单,但是xml文档是服务器的响应.是否可以在不写入文件的情况下执行此操作?尝试从内存中做到这一点非常好.

I'm new to python and I'm having a particularly difficult time working with xml and python. The situation I have is this, I'm trying to count the number of times a word appears in an xml document. Simple enough, but the xml document is a response from a server. Is it possible to do this without writing to a file? It would be great trying to do it from memory.

这是示例xml代码:

<xml>
  <title>Info</title>
    <foo>aldfj</foo>
      <data>Text I want to count</data>
</xml>

这是我在python中拥有的

Here is what I have in python

import urllib2
import StringIO
import xml.dom.minidom
from xml.etree.ElementTree import parse
usock = urllib.urlopen('http://www.example.com/file.xml') 
xmldoc = minidom.parse(usock)
print xmldoc.toxml()

过去,这一点我尝试使用StringIO,ElementTree和minidom均未成功,但到了不确定要做什么的地步.

Past This point I have tried using StringIO, ElementTree, and minidom to no success and I have gotten to a point where I'm not sure what else to do.

任何帮助将不胜感激

推荐答案

如果您只是想计算单词在XML文档中出现的次数,只需将文档作为字符串读取并进行计数:

If you are just trying to count the number of times a word appears in an XML document, just read the document as a string and do a count:

import urllib2
data = urllib2.urlopen('http://www.example.com/file.xml').read()
print data.count('foobar')

否则,您可以遍历要查找的标签:

Otherwise, you can just iterate through the tags you are looking for:

from xml.etree import cElementTree as ET
xml = ET.fromstring(urllib2.urlopen('http://www.example.com/file.xml').read())
for data in xml.getiterator('data'):
    # do something with
    data.text

这篇关于在Python中-解析响应xml并查找特定的文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆