2013-08-07 20 views
10

Jak ustawić pole tekstowe elementu ElementTree na podstawie jego konstruktora? Lub w poniższym kodzie, dlaczego jest drugi wydruk root.text Brak?Jak ustawić pole tekstowe ElementTree w konstruktorze?

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 

Tutaj wyjście:

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

Odpowiedz

7

Konstruktor nie obsługuje go:

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 = [] 

Jeśli zdasz text jako argument słowa kluczowego dla konstruktora, można dodać text przypisz do swojego elementu, co stało się w twoim drugim przykładzie.

+1

Dzięki! (Powinienem przeczytać kod zamiast dokumentacji!) –

3

Konstruktor nie pozwala na to, bo myśleli, że byłoby niewłaściwe, aby każdy foo=bar dodać atrybut wyjątkiem losowy dwa: text i tail

Jeśli uważasz, że to głupi powód, aby usunąć konstruktora komfort (tak jak ja), wtedy możesz stworzyć swój własny element. Zrobiłem. Mam go jako podklasę i dodano parametr parent. To pozwala ci nadal używać go ze wszystkim innym!

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) 
Powiązane problemy