python ElementTree the text of element who has a child
Asked Answered
B

2

5

When I try to read a text of a element who has a child, it gives None:

See the xml (say test.xml):

<?xml version="1.0"?>
<data>
    <test><ref>MemoryRegion</ref> abcd</test>
</data>

and the python code that wants to read 'abcd':

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print root.find("test").text

When I run this python, it gives None, rather than abcd.

How can I read abcd under this condition?

Bearable answered 31/10, 2013 at 6:36 Comment(1)
This was very annoying. It seams like 'abcd' is the text value of <test>.Eldaelden
P
5

Use Element.tail attribute:

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('test.xml')
>>> root = tree.getroot()
>>> print root.find(".//ref").tail
 abcd
Passementerie answered 31/10, 2013 at 6:46 Comment(0)
W
4

ElementTree has a rather different view of XML that is more suited for nested data. .text is the data right after a start tag. .tail is the data right after an end tag. so you want:

print root.find('test/ref').tail
Warga answered 31/10, 2013 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.