ElementTree element index look up

柔情痞子 提交于 2019-12-06 20:29:18

问题


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?


回答1:


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



回答2:


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



回答3:


def Alarms_Validation(self,path,AlarmNo,AlarmText,Severity,Text,Event):
    with open(path) as f:
        tree = et.parse(f)
        RUN=True
        root = tree.getroot()
        try:

                for x in xrange(10000):
                        print x
                        for y in xrange(6):
                                print y
                                if root[x][y].text==AlarmNo:
                                        print "found"
                                        print x
                                        print y
                                        if root[x][y+1].text!=AlarmText:
                                            print "Alarm text is not proper"
                                        else:
                                            print "Alarm Text is proper"
        except IndexError:
                pass


来源:https://stackoverflow.com/questions/3763048/elementtree-element-index-look-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!