Jackie
Jackie

Reputation: 129

How to check if a xpath/element exists in XML?

How to check, if a tag/xpath/element exists or not ?

Sample.xml

<layer>
    <value>Random</value>
    <value>12345</value>
</layer>
<layer>
    <value>Last_Name</value>
    <value>ABCD</value>
</layer>
<layer>
    <value>dynamic</value>
    <value>a1234bcd</value>
 </layer>

Sample.py

from lxml import etree
tree = etree.parse('sample.xml')
print tree.xpath('//layer[value="Last_Name"]/value')[1].text

Here, I'm trying to find the value of the tag 'Last_Name' i.e., ABCD How to check if an element 'Last_Name' exists or not ? Because, an exception is caught as "list index out of range". Is it possible to check if an element exists ?

Upvotes: 1

Views: 1152

Answers (1)

Marat
Marat

Reputation: 15738

Match by text; then get the content of the following sibling:

tree.xpath('//layer/value[text()="Last_Name"]/following-sibling::value/text()')

Upvotes: 1

Related Questions