ElementTree element index look up
Asked Answered
Q

3

15

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?

Quire answered 21/9, 2010 at 17:54 Comment(0)
P
13

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
Phloem answered 21/9, 2010 at 18:0 Comment(1)
Just a heads up - list(root).index(body) is now the proper way to do this. getchildren() has been deprecatedSeadog
O
0
import xml.etree.ElementTree as ET
root=ET.Element('C:\Users\Administrator\Desktop\ValidationToolKit_15.9\ValidationToolKit_15.9\NE3S_VTK\webservice\history\ofas.2017-1-3.10-55-21-608.xml')
childnew=ET.SubElement(root,"354")
root.getchildren().index(childnew)
0
list(root).index(childnew)
0
Obeah answered 4/1, 2017 at 7:30 Comment(1)
you may want to add a few words of explanation to this, i.e. "first create a list with getchildren() and then get its index with index()"Heliograph
O
-2
def alarms_validation(self, path, alarm_no, alarm_text):
    with open(path) as f:
        tree = et.parse(f)
        root = tree.getroot()
        try:
            for x in xrange(10000):
                print x
                for y in xrange(6):
                    print y
                    if root[x][y].text == alarm_no:
                        print "found"
                        if root[x][y+1].text != alarm_text:
                            print "Alarm text is not proper"
                        else:
                            print "Alarm Text is proper"
        except IndexError:
            pass
Obeah answered 5/1, 2017 at 8:46 Comment(5)
This is working according to my requirement. I am getting the index and one get the index i am validation strings. Above whatever is posted was not working for me.Obeah
How is this an answer to the question? It seems totally unrelated.Hoatzin
@Hoatzin Here Print x and Print y are the Index of element tree. Another approach to find the index.Obeah
Nobody can take your code as-is and test run it. It is not complete. It is not at all clear how it answers the question. What on earth does "Alarms_Validation" have to do with what is asked?Hoatzin
@Hoatzin you are absolutely correct that nobody can take this code as it is, but can take another approach to find the index of the sub-elements. Here Alarms related text, User please ignore. Just check that X and Y are the are the Indexes. ThanksObeah

© 2022 - 2024 — McMap. All rights reserved.