我有一个XML文件,我想使用Python的xml.etree读取其中的一些数据。
假设XML文件如下所示:
<a>
<b>
<c>
<d>This is the text I want to retrieve</d>
</c>
</b>
</a>我所做的是这样的:
document = ElementTree.parse('file.xml')
dToFind = document.find('d')
print(dToFind.text)但它给了我以下错误:
print(dToFind.text)
AttributeError: 'NoneType' object has no attribute 'text'我做错什么了?我怎么才能修好它呢?
谢谢!
发布于 2014-08-18 14:36:46
可以使用 for more sophesticated parsing和find递归地查找节点。
在这种情况下:
dToFind = document.find('.//d')文档指出使用xpath进行更结构化的解析--这将鼓励您研究这个问题。
演示
>>> from xml.etree import ElementTree as ET
>>> content = """<a>
... <b>
... <c>
... <d>This is the text I want to retrieve</d>
... </c>
... </b>
... </a>
... """
>>>
>>> xx = ET.fromstring(file) #you would be doing .parse()
>>> xx.find('d') #Returns None, as it finds only first level children
>>> xx.find('.//d')
<Element 'd' at 0xf1b550>
>>> d = xx.find('.//d')
>>> d.text
'This is the text I want to retrieve'https://stackoverflow.com/questions/25365725
复制相似问题