Добавление тега XML и атрибутов с открытым и закрытым тегом Python

1

Я пытаюсь построить 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>
Теги:
elementtree

1 ответ

0
Лучший ответ

Вам нужно установить "пустой" текст для элемента:

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

возвращает:

<root></root>
  • 0
    Мне пришлось добавить root.tail = '\ n', чтобы отделить каждое добавление, но root.text = '' предоставил тег open и close. Спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню