You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python ElementTree根据属性值筛选元素属性?

解决方案

要精准筛选出title属性值为President的Element元素,只需修改XPath查询表达式,从匹配所有含title属性的元素,改为匹配**属性值完全等于President**的元素即可。

修改后的代码

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)

# 精准匹配title属性值为'President'的Element元素
target = root.find(".//Element[@title='President']")
if target is not None:
    # 提取name和age属性并输出
    print(f"name: {target.attrib['name']}, age: {target.attrib['age']}")

关键修改点

  1. XPath表达式调整:将原来的.//*[@title]改为.//Element[@title='President'],其中:
    • .//Element:匹配所有层级下的Element标签
    • [@title='President']:筛选出title属性值严格等于President的元素
  2. 单个元素查询:因为你只需要单个元素,使用find()而非findall()更高效,它会返回第一个匹配的元素(如果存在)
  3. 属性提取:通过target.attrib['name']和target.attrib['age']直接获取目标属性值

如果需要处理可能不存在匹配元素的情况,记得添加if target is not None的判断,避免抛出AttributeError。

内容的提问来源于stack exchange,提问作者GrizzlyMcGee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:57:19