Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElementTree findall 'or' operator

If I have an xml file like this:

<root>
  <item>
    <prop>something</prop>
  </item>
  <test>
    <prop>something</prop>
  </test>
  <test2>
    <prop>something</prop>
  </test2>
</root>

I can use xmlTree.getroot().findall("item") to get all of the 'item' elements.

How would I get all of the 'item' OR 'test' elements? I want something like:

xmlTree.getroot().findall("item or test")

I didn't see anything like this in the examples in the documentation. Any ideas?

like image 357
David Doria Avatar asked Mar 21 '14 13:03

David Doria


1 Answers

Since ElementTree from stdlib provides only limited xpath support, you can use | xpath OR operator only if you are using lxml:

from lxml import etree as ET


data = """<?xml version="1.0"?>
<data>
<item>1</item>
<test>2</test>
</data>"""

tree = ET.fromstring(data)

for element in tree.xpath('//item|//test'):
    print element.text

prints:

1
2

In case of xml.etree.ElementTree you can combine the results of two separate findall() calls:

for element in tree.findall('.//item') + tree.findall('.//test'):
    print element.text

Or, check the tag name inside the loop:

for element in tree.iter():
    if element.tag in ('item', 'test'):
        print element.text
like image 200
alecxe Avatar answered Sep 20 '22 16:09

alecxe