我正在尝试构建以下xml。我希望能够向此xml附加更多<mcastChannel attrs></mcastChannel>
标签。我反而越来越。
我确实读过this answer,这是一个类似的问题,但是我无法将其附加到XML_STR_Config。
尝试构建的XML:
<?xml version="1.0"?>
<ewe mask="0x80" hw_type="100" br="SC" release="5.3.0-10">
<probe>
<core>
<setup>
<mcastnames>
<mclist xmlChildren="list">
<mcastChannel attrs></mcastChannel>
<mcastChannel attrs></mcastChannel>
</mclist>
</mcastnames>
</setup>
</core>
</probe>
</ewe>
我当前的代码:
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
CHANNEL_DATA = [['nameTest', '225.0.0.1']]
APPEND_CONFIG = ('mcastChannel name="{}" tuningId="{}" addr="{}"')
xml_root = ElementTree.ElementTree(
ElementTree.fromstring(XML_STR_CONFIG))
multicast_xml_child = xml_root.getroot()[0][0][0][0][0]
for tuning_id, data in enumerate(CHANNEL_DATA):
multicast_xml_child.append(Element(APPEND_CONFIG.format(data[0], tuning_id, data[1])))
xml_root.write(output_file, xml_declaration=True, encoding='utf-8', method='xml')
结果:
<?xml version='1.0' encoding='utf-8'?>
<ewe br="SC" hw_type="100" mask="0x80" release="5.4.0-10">
<probe>
<core>
<setup>
<mcastnames>
<mclist xmlChildren="list">
<mcastChannel name="test" tuningId="0" addr=""/>
<mcastChannel name="test" tuningId="1" addr="225.1.0.0"/>
</mcastnames>
</setup>
</core>
</probe>
</ewe>
答案 0 :(得分:0)
您需要为元素设置一个“空”文本:
root = etree.Element('root')
root.text = ''
print (etree.tostring(root))
返回:
<root></root>