Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElementTree element index look up

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 sub element?

like image 334
John Avatar asked Sep 21 '10 17:09

John


People also ask

How do I view XML files in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().

What is XML Etree ElementTree in Python?

The xml. etree. ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.


1 Answers

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
like image 121
Mark Avatar answered Oct 17 '22 02:10

Mark