我正在尝试创建一个导入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。
发布于 2019-09-06 16:16:25
我不确定您实际使用的是哪些库,但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>https://stackoverflow.com/questions/57818065
复制相似问题