将数组字典转换为python中的xml? [英] Converting an array dict to xml in python?
问题描述
我有一个需要转换为xml的数组.
I have this array that I need to convert to xml.
array = [
{
'time': {"hour":"1", "minute":"30","seconds": "40"}
},
{
'place': {"street":"40 something", "zip": "00000"}
}
]
xml应该具有一个标题,例如,我可以将其作为变量放入
The xml should have a title that I can put in as a variable for example,
xml_title = "test"
基于上面的数组和xml标题,我想要的结果是这样的:
The result I want based on the array above and the xml title is this:
<test>
<time hour="1" minute="30" second="40"></time>
<place>
<street>40 something</street>
<zip>00000</zip>
</place>
</test>
我喜欢类似的堆栈溢出问题( https://stackoverflow.com/a/18991263/875139),但是我很困惑如何使用该答案来获得期望的结果.
I liked the answer given in a similar stack overflow question (https://stackoverflow.com/a/18991263/875139) but I am confused how I can use that answer to get this desired result.
请帮助.
推荐答案
如注释中所述,您的原始问题混合了属性和元素.如果您希望将所有内容都用作元素,则可以使用 dicttoxml
.例如:
As noted in the comments, your original question mixes attributes and elements. If you want everything as elements, you might be able to use dicttoxml
. For example:
from dicttoxml import dicttoxml
array = [
{
'time': {"hour":"1", "minute":"30","seconds": "40"}
},
{
'place': {"street":"40 something", "zip": "00000"}
}
]
xml = dicttoxml(array, custom_root='test', attr_type=False)
产生以下XML:
<?xml version="1.0" encoding="UTF-8" ?>
<test>
<item>
<time>
<seconds>40</seconds>
<minute>30</minute>
<hour>1</hour>
</time>
</item>
<item>
<place>
<street>40 something</street>
<zip>00000</zip>
</place>
</item>
</test>
如果您可以将字典转换为:
If you can convert your dictionary to:
dictionary = {
'time': {"hour":"1", "minute":"30","seconds": "40"},
'place': {"street":"40 something", "zip": "00000"}
}
然后您的XML将显示为所需.
Then your XML will look as desired.
<?xml version="1.0" encoding="UTF-8" ?>
<test>
<place>
<street>40 something</street>
<zip>00000</zip>
</place>
<time>
<seconds>40</seconds>
<minute>30</minute>
<hour>1</hour>
</time>
</test>
请注意,通常不保证字典键的顺序,因此,如果要在 dict
中保留键的顺序,则可能需要签出
Note that, in general, the order of dictionary keys are not guaranteed, so if you want to preserve the order of keys in a dict
, you may want to check out collections.OrderedDict
.
这篇关于将数组字典转换为python中的xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!