python ElementTree the text of element who has a child

守給你的承諾、 提交于 2019-12-10 21:47:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!