2010-09-21 110 views
5

我使用xml.etree.ElementTree模块从另一个结构化文档中用Python 3.1创建XML文档。ElementTree元素索引查找

我可以使用哪个ElementTree函数返回现有子元素的索引?

回答

7

getchildren方法返回Element对象的子元素列表。然后您可以使用列表的内置索引方法。

>>> 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 
+0

谢谢,正是我一直在寻找。 – John 2010-09-21 18:12:25

+3

只是一个头 - 列表(根).index(身体)现在是这样做的正确方法。 getchildren()已被弃用 – aaaaaa 2014-12-30 00:49:26

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 
+0

您可能需要为此添加一些解释词,即“先用'getchildren()创建一个列表,然后用'index()'获得它的索引” – 2017-01-04 08:34:45

0
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 
+0

这是按照我的要求。 我得到的索引和一个得到索引我是验证字符串。 以上发布的内容不适合我。 – user2160906 2017-01-05 08:48:16

+0

这是如何回答这个问题?这似乎完全不相关。 – mzjn 2017-01-08 16:51:22

+0

@mzjn这里打印x和打印y是元素树的索引。 找到索引的另一种方法。 – user2160906 2017-01-10 11:07:04