python - 读取带有嵌套标签的 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.ElementTree
,getroot()
我得到了两个p
孩子。当我在第一个孩子中询问文本时,p
我得到“这是文本示例”。
如果我看第一个的孩子p
,我会用“就像我写的所有其他东西一样”的文字来加粗。
但我找不到“,\n这是一些永远隐藏的后续文本。”
其他p
孩子也是如此。
有没有办法得到它?
编辑:
我很困惑,因为唯一的孩子似乎是粗体斜体。我附上了一张带有代码的图片。
代码不起作用的示例:
解决方案
使用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.
推荐阅读
- python - Python - 如何检查 wordpress 网站版本
- python - Selenium登录问题到站点问题
- c# - 如何在 Datalist 的文本框中更新文本
- node.js - 如何在不中断长时间运行的请求的情况下将用户推送到另一个页面?
- java - 如何将字符串值与 uID Firebase 进行比较
- amazon-web-services - AWS:成员必须满足枚举值集:[WEB]
- angular - 无法在函数内调用 setAttribute
- javascript - jQuery - 使用本地存储和首选颜色方案切换暗模式
- c# - EF 试图创建泛型类型表 (TEntity)
- haskell - Haskell 中的函数优先级