【发布时间】:2018-05-24 16:16:05
【问题描述】:
我正在尝试解析具有一些文本的节点的 XML 文档,然后声明一个子节点,然后有更多的文本。例如,下面 XML 中的第二个“post”元素:
<?xml version="1.0"?>
<data>
<post>
this is some text
</post>
<post>
here is some more text
<quote> and a nested node </quote>
and more text after the nested node
</post>
</data>
我使用以下代码尝试打印出每个节点的文本:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
for child in root:
print (child.text)
但不幸的是,唯一的输出是:
this is some text
here is some more text
请注意,我错过了 and more text after the nested node 文本。
所以,
- 这是有效的 XML 吗?
- 如果是,如何使用 ElementTree 或其他 Python XML 库来实现所需的解析?
- 如果没有,除了编写我自己的解析器之外,还有什么解析 XML 的建议吗?
【问题讨论】:
标签: python xml elementtree