Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ElementTree to find a node - invalid predicate

I'm very new to this area so I'm sure it's just something obvious. I'm trying to change a python script so that it finds a node in a different way but I get an "invalid predicate" error.

import xml.etree.ElementTree as ET

tree = ET.parse("/tmp/failing.xml")
doc = tree.getroot()
thingy = doc.find(".//File/Diag[@id='53']")
print(thingy.attrib)
thingy = doc.find(".//File/Diag[BaseName = 'HTTPHeaders']")
print(thingy.attrib)

That should find the same node twice but the second find gets the error. Here is an extract of the XML:

<Diag id="53">
            <Formatted>xyz</Formatted>
            <BaseName>HTTPHeaders</BaseName>
            <Column>17</Column>

I hope I've not cut it down too much. Basically, finding it with "@id" works but I want to search on that BaseName tag instead.

Actually, I want to search on a combination of tags so I have a more complicated expression lined up but I can't get the simple one to work!

like image 296
Peter S Avatar asked May 26 '26 10:05

Peter S


1 Answers

The code in the question works when using Python 3.7. If the spaces before and after the equals sign in the predicate are removed, it also works with earlier Python versions.

thingy = doc.find(".//File/Diag[BaseName='HTTPHeaders']")

See https://bugs.python.org/issue31648.

like image 182
mzjn Avatar answered May 27 '26 22:05

mzjn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!