user159137 user159137 - 1 month ago 19
Python Question

xml.etree.ElementTree search tag by variable

I have a problem with the xml.etree.ElementTree Module in Python. I tried to search for a tag in the XML Tree using a variable:

i = "Http_Https"
print(xmldoc_ports.findall(".//*application-set/[name=i]/application/"))


But it looks like that it did not resolve the variable
i
.

Traceback (most recent call last):
File "test.py", line 223, in <module>
print(xmldoc_ports.findall(".//*application-set/[name=i]/application/"))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 749, in findall
return self._root.findall(path, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 390, in findall
return ElementPath.findall(self, path, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 293, in findall
return list(iterfind(elem, path, namespaces))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 263, in iterfind
selector.append(ops[token[0]](next, token))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 224, in prepare_predicate
raise SyntaxError("invalid predicate")


Is it possible to use a variable in the findall function?

Answer

The .//*application-set/[name=i]/application/ is not valid. I think you meant:

xpath = ".//application-set[@name='%s']/application" % i
print(xmldoc_ports.findall(xpath))

Note that @ before the name - this is how you show access the name attribute. Also, I've removed the / after the application-set and * before it.

Also, in order to have variable i inside the XPath, you should/can use string formatting. The %s is a placeholder for % operator to fill.

Comments