简体   繁体   中英

How to get XML tag value in Python

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?

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM