How to get XML tag value in Python

kalaracey picture kalaracey · Jul 5, 2012 · Viewed 53.7k times · Source

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?

Answer

Colin Dunklau picture Colin Dunklau · Jul 5, 2012

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]