2010-09-21 15 views
5

Sto utilizzando il modulo xml.etree.ElementTree per creare un documento XML con Python 3.1 da un altro documento strutturato.Indice elemento ElementTree cercare

Quale funzione ElementTree posso utilizzare per restituire l'indice di un sottoelemento esistente?

risposta

7

Il metodo getchildren restituisce un elenco di elementi secondari di un oggetto Element. È quindi possibile utilizzare il metodo di indice incorporato di un elenco.

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

Grazie, esattamente quello che stavo cercando. – John

+3

Solo un heads up - list (root) .index (body) è ora il modo corretto per farlo. getchildren() è stato deprecato – 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

potresti voler aggiungere qualche parola di spiegazione a questo, cioè "prima crea una lista con' getchildren() 'e poi ottieni il suo indice con' 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

Questo sta funzionando secondo il mio requisito Sto ottenendo l'indice e uno ottiene l'indice sono stringhe di convalida. Sopra quello che è stato pubblicato non funzionava per me. – user2160906

+0

Come è questa una risposta alla domanda? Sembra del tutto estraneo. – mzjn

+0

@mzjn Qui Stampa xe Stampa y sono l'indice dell'albero degli elementi. Un altro approccio per trovare l'indice. – user2160906

Problemi correlati