Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
199 views
Welcome To Ask or Share your Answers For Others

1 Answer

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...