gpt4 book ai didi

python - 从子节点之后的 XML 节点中提取文本

转载 作者:行者123 更新时间:2023-12-01 01:53:18 25 4
gpt4 key购买 nike

我正在尝试解析包含一些文本的节点的 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

请注意,我缺少文本以及嵌套节点后面的更多文本

所以,

  1. 这是有效的 XML 吗?
  2. 如果是,我如何使用 ElementTree 或其他 Python XML 库来实现所需的解析?
  3. 如果没有,除了编写我自己的解析器之外,还有什么解析 XML 的建议吗?

最佳答案

啊,在这里找到了答案:How can I iterate child text nodes (not descendants) in ElementTree?

基本上我必须使用子节点的.tail属性来访问之前丢失的文本。

关于python - 从子节点之后的 XML 节点中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50513894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com