【问题标题】:xmltodict and back again; attributes get their own tagxmltodict 并再次返回;属性获得自己的标签
【发布时间】: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


    【解决方案1】:

    我不确定您实际使用的是哪些库,但 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多