在Python中解析响应xml并找到特定文本值

10 投票
4 回答
22266 浏览
提问于 2025-04-17 03:45

我刚开始学习python,最近在处理xml和python的时候遇到了不少困难。我的情况是这样的,我想统计一个单词在xml文档中出现的次数。这听起来简单,但这个xml文档是从服务器返回的。有没有办法在不写入文件的情况下做到这一点?如果能直接在内存中处理就太好了。

这里有一段示例xml代码:

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

这是我在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,但都没有成功,现在我不知道该怎么办了。

任何帮助都将非常感激。

4 个回答

2

这有帮助吗...

from xml.etree.ElementTree import XML

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

# this will give us the contents of the data tag.
data = XML(txt).find("data").text

# ... so here we could do whatever we want
print data
5

这其实很简单,至少我觉得是这样:

import urllib2
from xml.dom import minidom

usock = urllib2.urlopen('http://www.example.com/file.xml') 
xmldoc = minidom.parse(usock)

for element in xmldoc.getElementsByTagName('data'):
  print element.firstChild.nodeValue

所以要计算一个字符串出现的次数,可以试试这个(虽然有点简化,但我喜欢用一行代码来写):

count = sum(element.firstChild.nodeValue.find('substring') for element in xmldoc.getElementsByTagName('data'))
5

如果你只是想计算一个词在XML文档中出现的次数,可以直接把文档当作字符串来读取,然后进行计数:

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

如果不是这样的话,你可以逐个检查你想要的标签:

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

撰写回答