I am trying to parse an xpath but it is giving Invalid expression error.
The code that should work:
JavaScript
x
3
1
x = tree.xpath("//description/caution[1]/preceding-sibling::*/name()!='warning'")
2
print(x)
3
Expected result is a boolean value but it is showing error:
JavaScript
1
8
1
Traceback (most recent call last):
2
File "poc_xpath2.0_v1.py", line 9, in <module>
3
x = tree.xpath("//description/caution[1]/preceding-sibling::*/name()!='warning'")
4
File "srclxmletree.pyx", line 2276, in lxml.etree._ElementTree.xpath
5
File "srclxmlxpath.pxi", line 359, in lxml.etree.XPathDocumentEvaluator.__call__
6
File "srclxmlxpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._handle_result
7
lxml.etree.XPathEvalError: Invalid expression
8
Advertisement
Answer
The exception is because name()
isn’t a valid node type. Your XPath would only be valid as XPath 2.0 or greater. lxml only supports XPath 1.0.
You would need to move the name() != 'warning'
into a predicate.
Also, if you want a True/False result, wrap the xpath in boolean()
…
JavaScript
1
2
1
tree.xpath("boolean(//description/caution[1]/preceding-sibling::*[name()!='warning'])")
2
Full example…
JavaScript
1
15
15
1
from lxml import etree
2
3
xml = """
4
<doc>
5
<description>
6
<warning></warning>
7
<caution></caution>
8
</description>
9
</doc>"""
10
11
tree = etree.fromstring(xml)
12
13
x = tree.xpath("boolean(//description/caution[1]/preceding-sibling::*[name()!='warning'])")
14
print(x)
15
This would print False
.