问题
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?
回答1:
Use Element.tail attribute:
>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('test.xml')
>>> root = tree.getroot()
>>> print root.find(".//ref").tail
abcd
回答2:
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
来源:https://stackoverflow.com/questions/19699889/python-elementtree-the-text-of-element-who-has-a-child