【问题标题】:Python parse XML content of an element when there is a child element当有子元素时,Python解析元素的XML内容
【发布时间】:2022-06-23 17:30:56
【问题描述】:

我有一个如下的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
    <data>
        <text>
            I have <num1>two</num1> apples and <num2>four</num2> mangoes
        </text>
    </data>

我想解析文件并获取text 及其子元素的整个上下文并将其分配给变量sentence

sentence = "I have two apples and four mangoes"

如何使用 Python ElementTree 做到这一点?

【问题讨论】:

标签: python xml elementtree


【解决方案1】:
xml = """
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <text>
        I have <num1>two</num1> apples and <num2>four</num2> mangoes
    </text>
</data>
"""
from xml.etree import ElementTree as ET
x_data = ET.fromstring(xml.strip())
all_text = list(x_data.findall(".//text")[0].itertext())
print(" ".join([text.strip() for text in all_text]))

从父节点遍历文本,并根据需要处理文本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2011-04-05
    • 1970-01-01
    • 2022-01-19
    • 2013-06-17
    • 2017-10-09
    • 1970-01-01
    相关资源
    最近更新 更多