Ste*_*ist 14 python xml elementtree
如何从其构造函数中设置ElementTree Element的文本字段?或者,在下面的代码中,为什么root.text的第二次打印无?
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
Run Code Online (Sandbox Code Playgroud)
这里输出:
<period units="months">6</period>
6
<period text="6" units="months" />
None
<period units="months">6</period>
6
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 11
构造函数不支持它:
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 = []
Run Code Online (Sandbox Code Playgroud)
如果text作为关键字参数传递给构造函数,则会text向元素添加属性,这是第二个示例中发生的情况.
构造函数不允许它,因为他们认为每次foo=bar添加一个属性是不合适的,除了随机的两个:text和tail
如果你认为这是一个愚蠢的理由去除构造函数的舒适(就像我一样),那么你可以创建自己的元素.我做到了.我把它作为子类并添加了一个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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)