首页 > 解决方案 > 读取带有嵌套标签的 xml

问题描述

我有一个看起来像这样的 xml 文件

<?xml version="1.0"?>
<data>
   <p>
   This is an example of text <bold>just as everything else I write</bold>,
   this is some follow-up text that is hidden for eternity.
   </p>
   <p>
   This is more text with an <italic>strange</italic> example.
   </p>
</data>

我正在使用 python 来阅读它。

当我使用函数解析时xml.etree.ElementTreegetroot()我得到了两个p孩子。当我在第一个孩子中询问文本时,p我得到“这是文本示例”。

如果我看第一个的孩子p,我会用“就像我写的所有其他东西一样”的文字来加粗。

但我找不到“,\n这是一些永远隐藏的后续文本。”

其他p孩子也是如此。

有没有办法得到它?

编辑:

我很困惑,因为唯一的孩子似乎是粗体斜体。我附上了一张带有代码的图片。

代码不起作用的示例:

代码不起作用的示例

标签: pythonxmlxml-parsingelementtree

解决方案


使用itertext()以获取所有文本p

import xml.etree.ElementTree as ET


xml = '''<?xml version="1.0"?>
<data>
   <p>
   This is an example of text <bold>just as everything else I write</bold>,
   this is some follow-up text that is hidden for eternity.
   </p>
   <p>
   This is more text with an <italic>strange</italic> example.
   </p>
</data>'''

root = ET.fromstring(xml)
for p in root.findall('.//p'):
  print(' '.join(p.itertext()))

输出

   This is an example of text  just as everything else I write ,
   this is some follow-up text that is hidden for eternity.
   

   This is more text with an  strange  example.

推荐阅读