python - 使用 Python 和 xml.etree 解析 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 = document.find('d')
print(dToFind.text)

但它给了我以下错误:

    print(dToFind.text)
AttributeError: 'NoneType' object has no attribute 'text'

我做错了什么?我该如何解决它?

谢谢!

最佳答案

您可以使用XPATH for more sophesticated parsingfind 结合用于递归查找节点

在这种情况下:

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/

相关文章:

python - Python 中的 map<int, vector<int>> 是什么?

python - 当参数是 Pandas DataFrame 等包对象时的 Docstrings Python 函数

java - 切换到第三个选项卡后 Tabhost 的内容被重置

html - 如何从 XSLT 输出与号 (&)

java - 如何摆脱出现在我的 Android 应用程序顶部的额外间距?

java - 如何在 Android 偏好设置中使用 DatePicker

python - 如何在 Vim 插件输出中为单词着色

python - 使用 Pyramid 服务文件

python - 如何使用 findall 打印正则表达式的结果?

c# - Ninject 和 XML 配置绑定(bind)