使用 ElementTree 解析时保留空元素

Retaining empty elements when parsing with ElementTree

使用 Python 3.4 和 ElementTree,我试图将子元素添加到 xml 文件,否则保留 xml 文件(以 UTF-16 编写)一模一样

我的代码:

 new = new_XML_file.xml
 tree = ET.parse(new)
 root = tree.getroot()
 new_element = ET.SubElement(root, 'RENAMED_SOUND_FILE')
 new_element.text=new.split('\')[num][:-4]+'.wav'
 tree.write(fake_path++new.split('\')[num], encoding='utf-16', xml_declaration=True)

我遇到的问题是在此过程中更改了空元素。例如:

<EMPTY_ELEMENT></EMPTY_ELEMENT> 

变成:

<EMPTY_ELEMENT />

我知道对于一台机器来说,这基本上是一回事,但我想保留较早的格式以供测试。

关于如何保留完整的空元素有什么想法吗?

根据 documentation,输出方法(无论您使用的是 tostring 方法还是 write)都有一个默认为 True 的 "short_empty_elements" 关键字。使这个 False 应该给你你想要的输出:

import xml.etree.ElementTree as ET

root=ET.Element("root")
print(ET.tostring(root,short_empty_elements=False))