0

我有以下字典结构

[{
    "Body" : [{
        "Universal Lift Support" : ["1\"-9\" Extended Length",
                                    "10\"-14.5\" Extended Length",
                                    "15\"-19\" Extended Length",
                                    "20\" + Extended Length"]
    }]

我想使用该dicttoxml库来获得所需的 xml 输出,例如:

<root>
    <Body>
        <Universal Lift Support>
            1"-9" Extended Length
            10"-14.5" Extended Length
            15"-19" Extended Length
            20" + Extended Length
        </Universal Lift Support>

但是,在应用下一个代码后:

dicttoxml.dicttoxml(result, attr_type=False, root=True)

我得到了像这样的xml结构:

<?xml version="1.0" encoding="UTF-8" ?><root><item><Body><item><Universal_Lift_Support><item>1&quot;-9&quot; Extended Length</item><item>10&quot;-14.5&quot; Extended Length</item><item>15&quot;-19&quot; Extended Length</item><item>

哪些选项可以帮助格式化和获取如上所述的输出?

4

3 回答 3

1

考虑使用遍历 json 对象并构建 XML 树的内置 Python 库(json,xml.etree.ElementTree和 to pretty print, )。xml.dom.minidom需要注意的一件事:XML 节点不能在名称中包含空格,所以它应该<UniversalLiftSupport>.

import json
import xml.etree.ElementTree as ET
import xml.dom.minidom

with open('BodyUniversal.json') as f:  
    jsondata = json.load(f)

# INITIALIZING XML DOC AND PARENT TAGS
root = ET.Element('root')
body = ET.SubElement(root, 'Body')
uls = ET.SubElement(body, 'UniversalLiftSupport')
uls.text = ''

# ITERATE THROUGH LIST, APPENDING TO XML
for i in jsondata[0]['Body'][0]['Universal Lift Support']:
    uls.text = uls.text + '\n\t\t\t' + i

# OUTPUT AND PRETTY PRINT TREE
tree_out = ET.tostring(root, encoding="UTF-8")
newXML = xml.dom.minidom.parseString(tree_out.decode('UTF-8'))
pretty_xml = newXML.toprettyxml()    

print(pretty_xml)
# <?xml version="1.0" ?>
# <root>
#         <Body>
#                 <UniversalLiftSupport>
#                         1&quot;-9&quot; Extended Length
#                         10&quot;-14.5&quot; Extended Length
#                         15&quot;-19&quot; Extended Length
#                         20&quot; + Extended Length</UniversalLiftSupport>
#         </Body>
# </root>

# OUTPUT XML CONTENT TO FILE
with open('Output.xml','w') as f:
    f.write(pretty_xml)
于 2017-07-05T20:48:58.397 回答
0

可能您必须编写一个函数来按照您想要的方式为列表生成 xml: https ://github.com/quandyfactory/dicttoxml/blob/master/dicttoxml.py

(见 dicttoxml 函数注释)

似乎“<item>whatever</item>”模式是硬编码的,如果你使用 cdata=True,你会得到整个 '<![CDATA[whatever]]>' 的东西。

于 2017-07-05T17:11:37.173 回答
0

如果该软件被称为 dicttoxml,那么我认为期望它生成 XML 是合理的。你说你想要的输出不是 XML,所以这个工具不生成它也就不足为奇了。您似乎在抱怨该产品按照锡上所说的那样做。

于 2017-07-05T19:44:33.660 回答