使用Python和XML.etree解析XML
我有一个XML文件,我想使用Python的使用Python和XML.etree解析XML,python,xml,Python,Xml,我有一个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 = d
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'
我做错了什么?我怎样才能修好它
谢谢 可以与find
组合使用,以递归方式查找节点
在这种情况下:
dToFind = document.find('.//d')
文档指出使用xpath
进行更结构化的解析,这将鼓励您对此进行研究
演示
>从xml.etree导入元素树作为ET
>>>content=”“”
...
...
…这是我要检索的文本
...
...
...
... """
>>>
>>>xx=ET.fromstring(文件)#您将执行.parse()
>>>xx.find('d')#返回None,因为它只查找第一级子级
>>>xx.find('.//d')
>>>d=xx.find('.//d')
>>>d.文本
'这是我要检索的文本'
>>> 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'