python - 如何在 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>
解决方案
可以使用 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>
推荐阅读
- javascript - 如何修复'php跳过我的if语句'
- docker - 如何区分 Docker Toolbox 和 Docker for Mac/Windows?
- r - 如果包含在包中,Shinyjs 切换不起作用
- ios - Flutter部分的iOS部分配置与开发
- visual-studio - 如何更改 Visual Studio 2019 中的文本颜色设置以匹配 VS2017 的样式?
- c - 获取成员定义名称给定成员定义地址?
- excel - 如何将集合项输出到新工作表中的列?
- node.js - 如何使用带有回调函数的异步等待
- php - 我无法使用 password_hash 登录
- tensorflow-lite - 将保存的模型转换为 tflite - 'image_tensor' 的形状无效 '[None, None, None, 3]'