如何在构造函数中设置ElementTree元素文本字段 [英] How to set ElementTree Element text field in the constructor

查看:156
本文介绍了如何在构造函数中设置ElementTree元素文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从ElementTree Element的构造函数设置其文本字段?或者,在下面的代码中,为什么第二次打印root.text无?

How do I set the text field of of ElementTree Element from its constructor? Or, in the code below, why is the second print of 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 属性的元素,这就是第二个示例中发生的情况。

If you pass text as a keyword argument to the constructor, you will add a text attribute to your element, which is what happened in your second example.

这篇关于如何在构造函数中设置ElementTree元素文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆