python - 在具有特定路径的 lxml 树中查找元素
问题描述
假设我有一个 XML 文件,如下所示:
my_data.xml
<?xml version="1.0" encoding="UTF-8"?>
<data>
<country name="Liechtenstein" xmlns="aaa:bbb:ccc:liechtenstein:eee">
<rank updated="yes">2</rank>
<holidays>
<christmas>Yes</christmas>
</holidays>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore" xmlns="aaa:bbb:ccc:singapore:eee">
<continent>Asia</continent>
<holidays>
<christmas>Yes</christmas>
</holidays>
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama" xmlns="aaa:bbb:ccc:panama:eee">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
<ethnicity xmlns="aaa:bbb:ccc:ethnicity:eee">
<malay>
<holidays>
<ramadan>Yes</ramadan>
</holidays>
</malay>
</ethnicity>
</data>
解析后:
xtree = etree.parse('my_data.xml')
xroot = xtree.getroot()
我想搜索带有标签的元素holidays
,但只能在ethnicity
. 这一行:
holiday_nodes = xroot.xpath('.//*[local-name()="holidays"]')
会给我所有的假期节点,像这样:
[<Element {aaa:bbb:ccc:liechtenstein:eee}holidays at 0x19013f926c0>,
<Element {aaa:bbb:ccc:singapore:eee}holidays at 0x19013f92880>,
<Element {aaa:bbb:ccc:ethnicity:eee}holidays at 0x19012cdc0c0>]
实现此搜索的语法是什么?谢谢。
解决方案
尝试以下 xpath ...
.//*[local-name()="ethnicity"]//*[local-name()="holidays"]
推荐阅读
- angular - 错误类型错误:当我尝试在 ngOnInit() 中修补值时,无法读取未定义的属性“形式”
- javascript - 如何使用 Hapi/bell 登录 Twitter 用户?
- matlab - 使不同的子图在matlab上具有相同的颜色范围
- mosquitto - Mosquitto Auth 插件通配符主题不起作用
- c# - 为 SyndicationFeed 标题使用与 Richtextbox 中的摘要不同的字体 - C#
- php - How to remove a specific number from string in PHP
- laravel-5 - 如何允许访客用户查看帖子,而无需登录
- ruby-on-rails - “在此操作中多次调用渲染和/或重定向”设计
- python - How to display one image after another using .after()
- vapor - 如何根据主机只公开一些路由