Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

python - Retaining empty elements when parsing with ElementTree

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...