首页 > 解决方案 > 如何在 python 中从 xml 中提取元素、子元素和完整路径?

问题描述

我想从 xml 中提取一个元素,包括子元素和完整路径。

如果这是我的 xml 文档:

<world>
    <countries>
        <country>
            <name>a</name>
            <description>a short description</description>
            <population>
                <now>250000</now>
                <2000>100000</2000>
            </population>
        </country>
        <country>
            <name>b</name>
            <description>b short description</description>
            <population>
                <now>350000</now>
                <2000>150000</2000>
            </population>
        </country>
    </countries>
</world>

我想基于 ('//country[name="a"] 的 xpath 表达式结束这个(见下文)

<world>
    <countries>
        <country>
            <name>a</name>
            <description>a short description</description>
            <population>
                <now>250000</now>
                <2000>100000</2000>
            </population>
        </country>
    </countries>
</world>

标签: pythonpython-3.xxml-parsing

解决方案


可以使用 xpath 和 lxml 来处理这种类型的事情。

但有一件事,其中一个 html 标签 ( <2000>) 是无效的,因为它不是以字母开头。如果您无法控制源,则必须在解析之前替换有问题的标签,然后在处理后再次替换它。

所以,一起来:

import lxml.html as lh
countries = """[your html above]"""
doc = lh.fromstring(countries.replace('2000','xxx'))

states = doc.xpath('//country')
for country in states:
    if country.xpath('./name/text()')[0]!='a':
        country.getparent().remove(country)
print(lh.tostring(doc).decode().replace('xxx','2000'))

输出:

<world>
    <countries>
        <country>
            <name>a</name>
            <description>a short description</description>
            <population>
                <now>250000</now>
                <2000>100000</2000>
            </population>
        </country>
        </countries>
</world>

推荐阅读