【发布时间】:2021-05-24 16:37:13
【问题描述】:
我想查找具有某些子元素的 xml 元素。子元素需要有一个给定的标签和一个设置为特定值的属性。
举一个具体的例子(基于official documentation)。我想找到所有具有neighbor 属性name="Austria" 的子元素的country 元素:
import xml.etree.ElementTree as ET
data = """<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<neighbor name="Malaysia" direction="N"/>
<partner name="Austria"/>
</country>
<country name="Panama">
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
"""
root = ET.fromstring(data)
我尝试过的没有成功:
countries1 = root.findall('.//country[neighbor@name="Austria"]')
countries2 = root.findall('.//country[neighbor][@name="Austria"]')
countries3 = root.findall('.//country[neighbor[@name="Austria"]]')
全部给出:
SyntaxError: 无效谓词
以下解决方案显然是错误的,因为发现的元素太多:
countries4 = root.findall('.//country/*[@name="Austria"]')
countries5 = root.findall('.//country/[neighbor]')
其中countries4 包含所有具有name="Austria" 属性的元素,但包括partner 元素。 countries5 包含所有具有 any 相邻元素作为子元素的元素。
【问题讨论】:
标签: python python-3.x elementtree