问题
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