ElementTree element index look up

John picture John · Sep 21, 2010 · Viewed 11.8k times · Source

I'm using the xml.etree.ElementTree module to create an XML document with Python 3.1 from another structured document.

What ElementTree function can I use that returns the index of an existing subelement?

Answer

Mark picture Mark · Sep 21, 2010

The getchildren method returns a list of sub-elements of an Element object. You could then use the built-in index method of a list.

>>> import xml.etree.ElementTree as ET
>>> root = ET.Element("html")
>>> head = ET.SubElement(root, "head")
>>> body = ET.SubElement(root, "body")
>>> root.getchildren().index(body)
1