使用ElementTree解析时保留空元素 [英] Retaining empty elements when parsing with ElementTree

查看:136
本文介绍了使用ElementTree解析时保留空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python 3.4和ElementTree,我试图将一个子元素添加到xml文件中,并保持xml文件(以UTF-16编写),否则完全相同。

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.

我的代码:

 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> 

成为:

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

推荐答案

每个文档,输出方法(无论您使用的是tostring方法还是编写方法)都有一个 short_empty_elements关键字,默认为True。将其设置为False应当为您提供所需的输出:

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

这篇关于使用ElementTree解析时保留空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆