追加 XML 标签和具有开始和结束标签 Python 的属性

Append XML tag and attributes that has open and close tag Python

我正在尝试构建下面的 xml。我希望能够向此 xml 附加更多 <mcastChannel attrs></mcastChannel> 标签。我得到的是 .

我确实读过 一个类似的问题,但我无法将其附加到 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>

您需要为元素设置 'empty' 文本:

root = etree.Element('root')
root.text = ''
print (etree.tostring(root))

returns:

<root></root>