Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python和XML.etree解析XML_Python_Xml - Fatal编程技术网

使用Python和XML.etree解析XML

使用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文件,我想使用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'
我做错了什么?我怎样才能修好它

谢谢

可以与
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'