How to get the value of an XML tag 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 to extract 6 in <value><text>6</text></value> using Python?

+7
source share
2 answers

BeautifulSoup is the easiest way to parse XML, as far as I know ...

And suppose you read the introduction, and then just use:

 soup = BeautifulSoup('your_XML_string') print soup.find('text').string 
+2
source

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 think 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] 
+13
source

All Articles