2013-08-07 23 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

構造不支持它:

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屬性到你的元素,這是你的第二個例子中發生的事情。

+1

謝謝! (我應該閱讀代碼而不是文檔!) –

3

構造不允許它,因爲他們認爲這將是不恰當的有充分foo=bar添加屬性除了隨機二: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) 
相關問題