Search code examples
pythonxmlpython-3.xparsingelementtree

Checking for the existence of children when using ElementTree for XML parsing in python


I am using the ElementTree XML API in python3 and have a question, which seems to be basic, I just did not find in the documentation the right function to do it. The starting point is that I consider an xml file whose name is given in the string name. I am looking for a function that checks whether a chld exists. by its name. Currently what I am doing is:

     import xml.etree.ElementTree as ET
     tree = ET.parse(name)
     root = tree.getroot()
     item = root.getchildren()[2]

because I know that the item I am looking in is in position 2 (the 3rd entry). But I would rather have something like:

     item = root.checkIfExists('itemName')

Can someone suggest a function for this? Or a better way to approach this? Thank you.


Solution

  • Quoting the documentation:

    Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag

    So, try:

    item = root.find('itemName')
    

    .find() returns None if no such element exists. .findall() returns an empty list in that case.

    Demonstration:

    import xml.etree.ElementTree as ET
    root = ET.XML('<root><item1/><item2/><itemName/></root>')
    assert root[2] is root.find('itemName')