Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
kalaracey Avatar asked Jul 05 '12 19:07

kalaracey


People also ask

How do I read an XML string in Python?

There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.


Video Answer


1 Answers

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]
like image 61
Colin Dunklau Avatar answered Oct 12 '22 13:10

Colin Dunklau