Search code examples
pythonxpathxml-parsingelementtreefindall

python elementtree xpath - insert variable in findall @name=VARIABLEHERE


Is it possible to pipe in a variable to the @name attribute?

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")]

I need to get all the values only from a specific actionlist filtered by its name and ignore all the other actionlists. It works fine with

[@name="ACTIONLISTNAME"]

but I´d like something like this:

X = ACTIONLISTNAME
[@name=X]

Thanks in advance!


Solution

  • Use string formatting:

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