Is there a way to match multiple elements in a tree using .findall()
?
I would like to do this:
trees = log.findall('element1' or 'element2')
This is my work around (which works in my case because I don't have both e1 and e2 in the same XML):
trees = log.findall('element1')
if not trees:
trees = log.findall('element2')
I am parsing XML files that have similar structures but different names. C# allows "element1 | element2" matching.
ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree breaks down the XML document in a tree structure that is easy to work with. When in doubt, print it out ( print(ET.
Parsing from strings and files. lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.
No, you can't. C# appears to be using XPath expressions, but the ElementTree XPath support for XPath queries is too limited and does not include the support for this.
You can use or
to pick your second search if the first is empty:
trees = log.findall('element1') or log.findall('element2')
because an empty result is false-y.
The alternative is to use lxml
, an ElementTree API implementation on top of libxml2
, which supports all of the XPath 1.0 spec. Then you can do:
log.xpath('.//(element1|element2)')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With