【问题标题】:Extract text from XML node that comes after child node从子节点之后的 XML 节点中提取文本
【发布时间】: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 文本。

所以,

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

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多