thaweatherman thaweatherman -4 years ago 171
Python Question

XPath invalid expression when tag name has curly braces

The name of the tag I am trying to get to is

{http://whitehatsec.com/XML-api-Vuln}description
. Conveniently every tag is prefixed with that lovely reference to the whitehat website. Unfortunately the
xpath
in
lxml
doesn't like it. I am currently trying
vuln_root[0].xpath('//\{http://whitehatsec.com/XML-api-Vuln\}description')
which should get me to the right node. However lxml keeps saying


File "test.py", line 23, in <module>
for s in vuln_root[0].xpath('//\{http://whitehatsec.com/XML-api-Vuln\}description'):
File "lxml.etree.pyx", line 1509, in lxml.etree._Element.xpath (src/lxml/lxml.etree.c:50725)
File "xpath.pxi", line 318, in lxml.etree.XPathElementEvaluator.__call__ (src/lxml/lxml.etree.c:146020)
File "xpath.pxi", line 238, in lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:145028)
File "xpath.pxi", line 224, in lxml.etree._XPathEvaluatorBase._raise_eval_error (src/lxml/lxml.etree.c:144883)
lxml.etree.XPathEvalError: Invalid expression


How can I get around this awful tag naming in my xpath? Thanks

Answer Source

The easiest approach here is to just map the namespace.

el.xpath('//vuln:description',
    namespaces={'vuln': 'http://whitehatsec.com/XML-api-Vuln'})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download