Python xmltodict : How to preserve XML element order?

标签 python xml xmltodict

我正在使用 xmltodict 进行 XML 解析/反解析,我需要在处理一个文档时保留 XML 元素的顺序。玩具 REPL 示例:

>>> import xmltodict
>>> xml = """
... <root>
...   <a />
...   <b />
...   <a />
... </root>
... """
>>> xmltodict.parse(xml)
OrderedDict([('root', OrderedDict([('a', [None, None]), ('b', None)]))])
>>> xmltodict.unparse(_)
'<?xml version="1.0" encoding="utf-8"?>\n<root><a></a><a></a><b></b></root>'

请注意,原始序列 [a, b, a] 被替换为 [a, a, b]。有没有办法用 xmltodict 保留原始顺序?

最佳答案

它不是 super 优雅,但 minidom 可以很好地完成这项工作:

import xml.dom.minidom as minidom

xml = """
<root>
<a />
<b />
<a />
</root>
"""
doc = minidom.parseString(xml)                  # or minidom.parse(filename)
root = doc.getElementsByTagName('root')[0]      # or doc.documentElement
items = [n for n in root.childNodes if n.nodeType == doc.ELEMENT_NODE]

for item in items:
    print item.nodeName

您当然可以使用像 lxml 这样的成熟的 DOM API,但是对于按文档顺序迭代某些节点的适度任务,这可能不是必需的。

关于Python xmltodict : How to preserve XML element order?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34636273/

相关文章:

xml - 如何使用 awk 在多个文件中第一次匹配模式后插入多行

xml - 使用 Swift 3 pretty-print XML

python - 如何通过一些修改将 xml 转换为字典?

python - 使用 xmltodict 在 python 中从 xml 文件创建 json 文件

python - Pandas 合并 Vlookup,KeyError : "[' Value'] not in index"

Python Post - 不断收到响应 400,但curl 有效

mysql - 加载 XML INFILE 和子列

python - Flask Api 解析返回错误的 xml post 请求

python - 如何为 pandas fillna() 方法中的不同列应用不同的方法参数

python - Pandas:如何在groupby之后将值分配给组的第一行?