2013-08-07 21 views
10

Come si imposta il campo di testo di ElementTree Element dal suo costruttore? O, nel codice qui sotto, perché è la seconda stampa di root.text None?Come impostare il campo di testo Elemento ElementTree nel costruttore

import xml.etree.ElementTree as ET 

root = ET.fromstring("<period units='months'>6</period>") 
ET.dump(root) 
print root.text 

root=ET.Element('period', {'units': 'months'}, text='6') 
ET.dump(root) 
print root.text 

root=ET.Element('period', {'units': 'months'}) 
root.text = '6' 
ET.dump(root) 
print root.text 

Ecco l'output:

<period units="months">6</period> 
6 
<period text="6" units="months" /> 
None 
<period units="months">6</period> 
6 

risposta

7

Il costruttore non la supporta:

class Element(object): 
    tag = None 
    attrib = None 
    text = None 
    tail = None 

    def __init__(self, tag, attrib={}, **extra): 
     attrib = attrib.copy() 
     attrib.update(extra) 
     self.tag = tag 
     self.attrib = attrib 
     self._children = [] 

Se si passa text come argomento parola chiave per il costruttore, si aggiungerà un text attributo al tuo elemento, che è ciò che è successo nel tuo secondo esempio.

+1

Grazie! (Avrei dovuto leggere il codice invece della documentazione!) –

3

Il costruttore non consente per questo, perché hanno pensato che sarebbe improprio avere ogni foo=bar aggiungere un attributo ad eccezione del caso due: text e tail

Se si pensa che questo è un motivo stupido per rimuovere costruttore comfort (come faccio io) quindi puoi creare il tuo elemento. L'ho fatto. Ce l'ho come sottoclasse e ho aggiunto un parametro parent. Questo ti permette di usarlo ancora con tutto il resto!

Python 2.7:

import xml.etree.ElementTree as ET 

# Note: for python 2.6, inherit from ET._Element 
#  python 2.5 and earlier is untested 
class TElement(ET.Element): 
    def __init__(self, tag, text=None, tail=None, parent=None, attrib={}, **extra): 
     super(TextElement, self).__init__(tag, attrib, **extra) 

     if text: 
      self.text = text 
     if tail: 
      self.tail = tail 
     if not parent == None: # Issues warning if just 'if parent:' 
      parent.append(self) 

Python 2.6:

#import xml.etree.ElementTree as ET 

class TElement(ET._Element): 
    def __init__(self, tag, text=None, tail=None, parent=None, attrib={}, **extra): 
     ET._Element.__init__(self, tag, dict(attrib, **extra)) 

     if text: 
      self.text = text 
     if tail: 
      self.tail = tail 
     if not parent == None: 
      parent.append(self) 
Problemi correlati