![](/img/trans.png)
[英]Python ElementTree - Select a nested xml element based on the value of an attribute
[英]Python ElementTree - select element attributes based on value of 1 attribute
我试图 select 仅基于属性值的 1 个元素行。 例如,在下面的代码中我只想 select 其中title ='President'的名字和年龄。 我将如何 go 这样做?
from xml.etree import ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Report>
<Element name='Bob' age='32' title='President'></Element>
<Element name='Sue' age='25' title='Vice-President'></Element>
<Element name='Mary' age='44' title='Secretary'></Element>
</Report>'''
root = ET.fromstring(xml)
for target in root.findall('.//*[@title]'):
print(target.tag, target.attrib)
您可以使用 XPath 表达式来获取您的元素:
root.find("*[@title='President']")
# ^ Seach in child elements as well
# ^ Filter items with a predicate
# ^ the "title"-attribute must be 'President'
要获取您的姓名和年龄属性,您可以执行以下操作:
element = root.find("*[@title='President']")
print(element.attrib["name"], element.attrib["age"])
您可以在此处找到有关支持的标准库 XPath 的说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.