user159137 user159137 - 1 year ago 150
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"

But it looks like that it did not resolve the variable

Traceback (most recent call last):
File "", line 223, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/", line 749, in findall
return self._root.findall(path, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/", line 390, in findall
return ElementPath.findall(self, path, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/", line 293, in findall
return list(iterfind(elem, path, namespaces))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/", 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/", line 224, in prepare_predicate
raise SyntaxError("invalid predicate")

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

Answer Source

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

xpath = ".//application-set[@name='%s']/application" % i

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download