我有一个 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'
我做错了什么?我该如何解决它?
谢谢!
最佳答案
您可以使用XPATH
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'
关于python - 使用 Python 和 xml.etree 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25365725/