python - 检测并控制 Python 中自关闭 xml 元素的创建?

标签 python xml elementtree

也许我忽略了,但我在documentation中没有找到这个.

在Python的ElementTree中解析xml时,如何检测element|tag|node是否为self-closing (或未配对,即以 /> 结尾)或不?

创建 xml 文件时,如何明确声明我是否支持 self-closing ( /> ) 或 explicitly closed (即 </example> )xml 标签?

如果 ElementTree 没有,其他 python 解析器是否能更好地处理这个问题?

最佳答案

此问题已于 2014 年 3 月由 python 3.4 解决。它添加了 short_empty_elements ElementTree 的所有序列化函数的参数。

>>> from xml.etree import ElementTree as ET
>>> msg = ET.Element('msg',{'x': 'y'})
>>> ET.tostring(msg)
b'<msg x="y" />'
>>> ET.tostring(msg, short_empty_elements=False)
b'<msg x="y"></msg>'

关于python - 检测并控制 Python 中自关闭 xml 元素的创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14773668/

相关文章:

python - 为什么将 U 和 V channel 设置为 0 会导致显示蓝色图片?

python - 在 PyInstaller 下生成 x32 和 x64 版本

python - 在 Raspberry 上使用 Python 进行传感器监控

java - 从 Java 读取 XML 字符串

python - 流: How to distribute reinforcement vehicles (RL) vehicles uniformly?

Java Dom 解析器报告错误的子节点数

c# - 当元素大小写不一致时反序列化/读取 xml。

python - ElementTree : Element. remove() 跳跃迭代

python - 为什么在一个脚本中两次调用 ElementTree.parse 函数会出现异常?

python /元素树 : Write to file without namespaces