Reputation: 4783
I have next xml :
<a>
<aa id = 1>
<data>aaaa</data>
</aa>
<aa id = 2>
<data>bbbb</data>
</aa>
<aa id = 3>
<data>cccc</data>
</aa>
</a>
I would like to reach the data's text (aaaa,bbbb...) How can I do it ? (I've been using etree.ElementTree package)
Upvotes: 0
Views: 254
Reputation: 37269
You could try this:
In [1]: import xml.etree.ElementTree as ET
In [2]: tree = ET.parse('test.xml')
In [3]: root = tree.getroot()
In [4]: for el in root:
...: print el.find('data').text
...:
...:
aaaa
bbbb
cccc
The only thing that you are missing from the code you provided is elem.find('data').text
(inside of your for
loop`) - that will return the value you are looking for.
Upvotes: 1
Reputation: 4783
tree = xml.parse(file)
root = tree.getroot()
listElem = root.findall("aa")
for elem in listElem:
tmp1 = elem.findall("data")
str = tmp1[0].text
Upvotes: 0
Reputation: 9704
XML file:
<?xml version="1.0"?>
<a>
<aa id="1">
<data>aaaa</data>
</aa>
<aa id="2">
<data>bbbb</data>
</aa>
<aa id="3">
<data>cccc</data>
</aa>
</a>
You can use an XPath
query:
from lxml import etree
xml = etree.parse('/tmp/a.xml')
xml.xpath('.//data/text()')
['aaaa', 'bbbb', 'cccc'] #returns that
Upvotes: 1