Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing XML file in python

I have a XML file such as:

<?xml version="1.0" encoding="utf-8"?>
<result>
  <data>
    <_0>stream1</_0>
    <_1>file</_1>
    <_2>livestream1</_2>
  </data>
</result>

I used

xmlTag = dom.getElementsByTagName('data')[0].toxml()
xmlData=xmlTag.replace('<data>','').replace('</data>','')

and i got xmlData

<_0>stream</_0>
<_1>file</_1>
<_2>livestream1</_2>

but i need values stream,file,livestream1 etc.

How to do this?

like image 404
user1455438 Avatar asked Aug 25 '26 07:08

user1455438


2 Answers

I would suggest to use ElementTree. It's faster than the usual DOM implementations and I think its more elegant as well.

from xml.etree import ElementTree

#assuming xml_string is your XML above
xml_etree = ElementTree.fromstring(xml_string)
data = xml_etree.find('data')
for elem in data:
    print elem.text

Output would be:

stream1
file
livestream1
like image 144
Torsten Engelbrecht Avatar answered Aug 26 '26 22:08

Torsten Engelbrecht


For your information, this is how to do it with lxml and xpath:

from lxml import etree
doc = etree.fromstring(xml_string)
for elem in doc.xpath('//data/*'):
    print elem.text

The output should be the same:

stream1
file
livestream1
like image 43
Kien Truong Avatar answered Aug 26 '26 22:08

Kien Truong