python - 如何在构造函数中设置 ElementTree 元素文本字段

标签 python xml elementtree

如何从构造函数中设置 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/

相关文章:

python - 禁止 Django 自引用外键指向自身对象

python - 在Python中对字典进行排序

python - 为什么我们在这里需要字节顺序?

python - 使用查找方法(xml.etree.ElementTree)后获取父元素

python - Django 测试客户端与 django-pytest

java - 将 Element 对象转换为 Int?

xml - 为什么此 XML header 标记无效?

android - 如何让我的抽屉导航始终位于所有内容之上?安卓

python - 将值添加到嵌套字典时出错(python)

python - 解析 XML 异常