How to get XML tag value in Python

2019-06-16 04:57发布

I have some XML in a unicode-string variable in Python as follows:

<?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>

How do I extract the 6 in <value><text>6</text></value> using Python?

2条回答
甜甜的少女心
2楼-- · 2019-06-16 05:12

With 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

Edit: But I imagine there could be more than one result...

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]
查看更多
Summer. ? 凉城
3楼-- · 2019-06-16 05:29

BeautifulSoup is the most simple way to parse XML as far as I know...

And assume that you have read the introduction, then just simply use:

soup = BeautifulSoup('your_XML_string')
print soup.find('text').string
查看更多
登录 后发表回答