如何在Python中获取XML标记值

时间:2012-07-05 19:25:34

标签: python xml parsing dom xml-parsing

我在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>

2 个答案:

答案 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