【发布时间】:2019-09-06 08:07:27
【问题描述】:
我正在尝试创建一个导入 XML 的东西,将一些值与另一个 XML 中的值或 Oracle 数据库中的值进行比较,然后将其重新写回并更改一些值。我尝试过简单地导入 xml,然后再次导出,但这已经给我带来了问题; xml 属性不再显示为标签中的属性,而是拥有自己的子标签。
我认为这与here 描述的问题相同,其中最重要的答案是该问题已经存在多年。我希望你们知道一种解决此问题的优雅方法,因为我唯一能想到的就是在导出后进行替换。
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。
【问题讨论】:
标签: python attributes xmltodict dicttoxml