user1455438
user1455438

Reputation: 31

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?

Upvotes: 3

Views: 264

Answers (2)

Kien Truong
Kien Truong

Reputation: 11381

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

Upvotes: 1

Torsten Engelbrecht
Torsten Engelbrecht

Reputation: 13496

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

Upvotes: 2

Related Questions