2010-09-21 108 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