3

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.