2013-08-07 3 views
10

ElementTree 요소의 텍스트 필드를 해당 생성자에서 설정하는 방법은 무엇입니까? 또는 아래 코드에서 root.text의 두 번째 인쇄가 표시되지 않는 이유는 무엇입니까? 여기생성자에서 ElementTree 요소 텍스트 필드를 설정하는 방법

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 

출력 :

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

답변

7

생성자를 지원하지 않는 : 당신이 생성자에 대한 키워드 인자로 text을 전달하면

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

, 당신은 text를 추가합니다 속성을 요소에 추가합니다. 이는 두 번째 예제에서 발생한 것입니다.

그들이 모든 foo=bar는 제외 속성을 추가해야하는 것이 부적절하다고 생각했기 때문에 생성자는 허용하지 않습니다
+1

감사합니다! (나는 문서 대신 코드를 읽어야했다!) –

3

임의의 두 : texttail

이 생성자를 제거하는 바보 같은 이유를 생각한다면 위로 (내가하는 것처럼) 다음 자신의 요소를 만들 수 있습니다. 나는 그랬다. 하위 클래스로 가지고 있고 parent 매개 변수를 추가했습니다. 이렇게하면 다른 모든 것들과 함께 사용할 수 있습니다!

파이썬 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) 

파이썬 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) 
관련 문제