使用dicttoxml自定义字典转换?

时间:2017-10-27 14:05:12

标签: python xml dictionary dicttoxml

我想在python中将字典转换为xml,我正在使用dicttoxml。我的代码如下所示:

>>> import os
>>> filepath=os.path.normpath('C:\\Users\\\\Desktop\\abc\\bc.txt')
>>> with open(filepath,'r') as f:
...     for line in f:
...             x=line.split(':')
...             x[-1]=x[-1].strip()
...             a=x[0]
...             b=x[1]
...             d[a]=b
...     xml = dicttoxml(d,custom_root='doc',attr_type=False)
...     xml2 = parseString(xml)
...     xml3 = xml2.toprettyxml()
...     print( xml3 )

输出如下:

<?xml version="1.0" ?>
<doc>
        <key name="product/productId">B000GKXY34</key>
        <key name="product/title">Nun Chuck, Novelty Nun Toss Toy</key>
        <key name="product/price">17.99</key>
        <key name="review/userId">ADX8VLDUOL7BG</key>
        <key name="review/profileName">M. Gingras</key>
        <key name="review/helpfulness">0/0</key>
        <key name="review/score">5.0</key>
        <key name="review/time">1262304000</key>
        <key name="review/summary">Great fun!</key>
        <key name="review/text">Got these last Christmas as a gag gift. They are great fun, but obviously this is not a toy that lasts!</key>
</doc>

但我想将key name替换为field name

<field name="product/productId">B000GKXY34</field>

这是由代码生成的字典:

{'product/productId': 'B000GKXY34', 'product/title': 'Nun Chuck, Novelty Nun Toss Toy', 'product/price': '17.99', 'review/userId': 'ADX8VLDUOL7BG', 'review/profileName': 'M. Gingras', 'review/helpfulness': '0/0', 'review/score': '5.0', 'review/time': '1262304000', 'review/summary': 'Great fun!', 'review/text': 'Got these last Christmas as a gag gift. They are great fun, but obviously this is not a toy that lasts!'}

而且我想在一个新文件中编写xml,我正在尝试使用write函数,但它不能正常工作:

with open ('filename','w') as output:
            output.write(xml3)

2 个答案:

答案 0 :(得分:1)

根据dicttoxml documentation

定义自定义项目名称

从版本1.7开始,如果您不希望列表中的项元素被称为“item”,则可以使用将父元素名称(即列表名称)作为参数的函数指定元素名称

>>> import dicttoxml
>>> obj = {u'mylist': [u'foo', u'bar', u'baz'], u'mydict': {u'foo': u'bar', u'baz': 1}, u'ok': True}
>>> my_item_func = lambda x: 'list_item'
>>> xml = dicttoxml.dicttoxml(obj, item_func=my_item_func)
>>> print(xml)
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <mydict type="dict">
    <foo type="str">bar</foo>
    <baz type="int">1</baz>
  </mydict>
  <mylist type="list">
    <list_item type="str">foo</list_item>
    <list_item type="str">bar</list_item>
    <list_item type="str">baz</list_item>
  </mylist>
  <ok type="bool">True</ok>
</root>

答案 1 :(得分:0)

从文档中,我们必须使用一个函数来提供xml的自定义键名称。

参考-dicttoxml github

>>> import os
>>> filepath=os.path.normpath('C:\\Users\\\\Desktop\\abc\\bc.txt')
>>> with open(filepath,'r') as f:
...     for line in f:
...             x=line.split(':')
...             x[-1]=x[-1].strip()
...             a=x[0]
...             b=x[1]
...             d[a]=b
...     returnfield = lambda x: 'field'
...     xml = dicttoxml(d,custom_root='doc',attr_type=False, item_func=returnfield)
...     xml2 = parseString(xml)
...     xml3 = xml2.toprettyxml()
...     print( xml3 )

输出为:

<?xml version="1.0" ?>
<doc>
        <field name="product/productId">B000GKXY34</field>
        <field name="product/title">Nun Chuck, Novelty Nun Toss Toy</field>
        <field name="product/price">17.99</field>
        <field name="review/userId">ADX8VLDUOL7BG</field>
        <field name="review/profileName">M. Gingras</field>
        <field name="review/helpfulness">0/0</field>
        <field name="review/score">5.0</field>
        <field name="review/time">1262304000</field>
        <field name="review/summary">Great fun!</field>
        <field name="review/text">Got these last Christmas as a gag gift. They are great fun, but obviously this is not a toy that lasts!</field>
</doc>