xmltodict 并再次返回;属性有自己的标签

xmltodict and back again; attributes get their own tag

我正在尝试创建导入 XML 的内容,将其中一些值与另一个 XML 中的值或 Oracle 数据库中的值进行比较,然后用一些值再次写回值改变了。我试过简单地导入 xml 然后再次导出它,但这已经给我带来了问题; xml 属性不再显示为标签内的属性,而是拥有自己的子标签。

我认为这与 中描述的问题相同,其中最重要的答案说该问题已经存在多年。我希望你们知道解决此问题的优雅方法,因为我唯一能想到的就是在导出后进行替换。

import xmltodict
from dicttoxml import dicttoxml

testfile = '<Testfile><Amt Ccy="EUR">123.45</Amt></Testfile>'
print(testfile)
print('\n')

orgfile = xmltodict.parse(testfile)
print(orgfile)
print('\n')

newfile = dicttoxml(orgfile, attr_type=False).decode()
print(newfile)

结果:

D:\python3 Test.py
<Testfile><Amt Ccy="EUR">123.45</Amt></Testfile>


OrderedDict([('Testfile', OrderedDict([('Amt', OrderedDict([('@Ccy', 'EUR'), ('#
text', '123.45')]))]))])


<?xml version="1.0" encoding="UTF-8" ?><root><Testfile><Amt><key name="@Ccy">EUR
</key><key name="#text">123.45</key></Amt></Testfile></root>

您可以看到输入标签 Amt Ccy="EUR" 已转换为带有子标签的 Amt。

我不确定您实际使用的是哪些库,但是 xmltodict 有一个 unparse 方法,它完全符合您的要求:

import xmltodict

testfile = '<Testfile><Amt Ccy="EUR">123.45</Amt></Testfile>'
print(testfile)
print('\n')

orgfile = xmltodict.parse(testfile)
print(orgfile)
print('\n')

newfile = xmltodict.unparse(orgfile, pretty=False)
print(newfile)

输出:

<Testfile><Amt Ccy="EUR">123.45</Amt></Testfile>


OrderedDict([('Testfile', OrderedDict([('Amt', OrderedDict([('@Ccy', 'EUR'), ('#text', '123.45')]))]))])


<?xml version="1.0" encoding="utf-8"?>
<Testfile><Amt Ccy="EUR">123.45</Amt></Testfile>