Retaining empty elements when parsing with ElementTree

梦想的初衷 提交于 2020-01-26 04:57:19

问题


Using Python 3.4 and ElementTree, I'm trying to add a sub-element to an xml file, keeping the xml file (written in UTF-16) otherwise exactly the same.

My code:

 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)

The problem I'm having is that empty elements are being changed in this process. For example:

<EMPTY_ELEMENT></EMPTY_ELEMENT> 

becomes:

<EMPTY_ELEMENT />

I know that to a machine, this is basically the same thing, but I'd like to retain the earlier formatting for testing purposes.

Any ideas on how I can retain the full empty elements?


回答1:


Per the documentation, output methods (whether you're using tostring methods or write) have a "short_empty_elements" keyword that defaults to True. Making this False should give you your desired output:

import xml.etree.ElementTree as ET

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


来源:https://stackoverflow.com/questions/38022862/retaining-empty-elements-when-parsing-with-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!