【问题标题】:how do I extract an element, sub-elements and the full path from xml in python?如何在 python 中从 xml 中提取元素、子元素和完整路径?
【发布时间】:2021-05-03 00:00:24
【问题描述】:

我想从 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>

【问题讨论】:

  • 感谢您的回答。我打错了。应该是y2000。有没有办法提取该元素而不是删除不匹配的元素? xml 文档还包含其他元素

标签: python python-3.x xml-parsing


【解决方案1】:

这种事情可以用xpath和lxml来处理。

但有一点,其中一个 html 标签 (&lt;2000&gt;) 是无效的,因为它不是以字母开头。如果你无法控制来源,则必须在解析前替换有问题的标签,然后在处理后再次替换。

所以,一起来:

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>

【讨论】:

  • 感谢您的回答。我打错了。应该是y2000。有没有办法提取该元素而不是删除不匹配的元素? xml 文档还包含其他元素
猜你喜欢
  • 2013-08-24
  • 2013-11-06
  • 2021-05-16
  • 2015-05-05
  • 2018-04-09
  • 2020-12-19
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多