2013-08-07 5 views
10

ElementTree要素のテキストフィールドをコンストラクタから設定するにはどうすればよいですか?または、以下のコードで、なぜroot.textの2番目の印刷がありませんか?コンストラクタの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

コンストラクタはそれをサポートしていません:

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を渡した場合、あなたはtextを追加しますあなたの要素への属性、これはあなたの2番目の例で起こったことです。彼らはすべてのfoo=barがランダム2以外の属性を追加する持っている不適切だろうと思ったので

+1

ありがとう! (私はドキュメントの代わりにコードを読んでいたはずです!) –

3

コンストラクタはそれを許可しない:texttail

あなたがこのコンストラクタを除去するためのダムの理由であると考えられる場合(私がそうするように)快適さがあれば、あなた自身の要素を作ることができます。やった。私はそれをサブクラスとして持ち、parentパラメータを追加しました。これにより、他のすべてとでもそれを使用することができます!

の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) 
関連する問題