python elementtree xpath-在findall @ name = VARIABLEHERE中插入变量

问题描述 投票:0回答:2

是否可以将变量传递到@name属性?

import xml.etree.ElementTree as ET
tree = ET.parse('C:/test.xml')
root = tree.getroot()

somelist = [x.text for x in root.findall(".//actionList[@name='VARIABLEHEREinsteadoftext']//value")]

我仅需要从按名称过滤的特定操作列表中获取所有值,并忽略所有其他操作列表。与

一起正常工作
[@name="ACTIONLISTNAME"]

但是我想要这样的东西:

X = ACTIONLISTNAME
[@name=X]

提前感谢!

python xpath xml-parsing elementtree findall
2个回答
3
投票

使用字符串格式

value = "ACTIONLISTNAME"
root.findall(".//actionList[@name='%s']//value" % value)

0
投票

@ alecxe的字符串格式答案很好用,但是如果您想使用F-strings formatting,则可以这样做:

请注意在模式部分中转义的双大括号

xml_element.findall(f"{{x-schema:schema.xml}}row[@{attribute_name}='{attribute_value}']")
© www.soinside.com 2019 - 2024. All rights reserved.