如何从构造函数中设置 ElementTree 元素的文本字段?或者,在下面的代码中,为什么 root.text 的第二次打印为 None?
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
最佳答案
构造函数不支持:
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
属性,这就是您的第二个示例中发生的情况。
关于python - 如何在构造函数中设置 ElementTree 元素文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093843/