xml.etree.ElementTree search tag by variable
<p>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:</p>

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

<p>But it looks like that it did not resolve the variable <code>i</code>.</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "test.py", line 223, in &lt;module&gt;
    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")
</code></pre>

<p>Is it possible to use a variable in the findall function?</p>

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

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

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

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

python xml-parsing