我在Python中的unicode-string变量中有一些XML,如下所示:
<?xml version='1.0' encoding='UTF-8'?>
<results preview='0'>
<meta>
<fieldOrder>
<field>count</field>
</fieldOrder>
</meta>
<result offset='0'>
<field k='count'>
<value><text>6</text></value>
</field>
</result>
</results>
如何使用Python提取6
中的<value><text>6</text></value>
?
答案 0 :(得分:16)
使用lxml:
import lxml.etree
# xmlstr is your xml in a string
root = lxml.etree.fromstring(xmlstr)
textelem = root.find('result/field/value/text')
print textelem.text
编辑:但我想可能会有不止一个结果......
import lxml.etree
# xmlstr is your xml in a string
root = lxml.etree.fromstring(xmlstr)
results = root.findall('result')
textnumbers = [r.find('field/value/text').text for r in results]
答案 1 :(得分:3)
BeautifulSoup是解析XML的最简单方法......
并假设您已阅读介绍,然后只需使用:
soup = BeautifulSoup('your_XML_string')
print soup.find('text').string