2010-09-21 13 views
5

J'utilise le module xml.etree.ElementTree pour créer un document XML avec Python 3.1 à partir d'un autre document structuré.Recherche d'index d'éléments ElementTree

Quelle fonction ElementTree puis-je utiliser qui retourne l'index d'un sous-élément existant?

Répondre

7

La méthode getchildren renvoie une liste de sous-éléments d'un objet Element. Vous pouvez ensuite utiliser la méthode d'index intégrée d'une liste.

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

Merci, exactement ce que je cherchais. – John

+3

Juste un heads-up - liste (root) .index (corps) est maintenant la bonne façon de le faire. getchildren() a été déprécié – aaaaaa

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

vous pouvez ajouter quelques mots d'explication à ceci, c.-à-d. "d'abord créer une liste avec' getchildren() 'et ensuite obtenir son index avec' index() '" –

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

Ceci fonctionne selon mon exigence. Je reçois l'index et on obtient l'index je suis des chaînes de validation. Ci-dessus tout ce qui est posté ne fonctionnait pas pour moi. – user2160906

+0

Comment est-ce une réponse à la question? Cela semble totalement sans rapport. – mzjn

+0

@mzjn Ici Imprimer x et Imprimer y sont l'index de l'arbre des éléments. Une autre approche pour trouver l'index. – user2160906