首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >xmltodict;属性有自己的标签

xmltodict;属性有自己的标签
EN

Stack Overflow用户
提问于 2019-09-06 16:07:28
回答 1查看 155关注 0票数 0

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

我认为这与here所描述的问题是相同的,在上面的答案中,这个问题已经存在多年了。我希望你们知道一个优雅的方法来解决这个问题,因为我唯一能想到的就是在导出后做一个替换。

代码语言:javascript
复制
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)

结果:

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-06 16:16:25

我不确定您实际使用的是哪些库,但xmltodict有一个unparse方法,它可以执行您想要的操作:

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
<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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57818065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档