用dicttoxml定制字典转换?

2024-05-26 11:13:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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 )

输出如下:

^{pr2}$

但是我想用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)

Tags: namefield字典osaswithlinexml
2条回答

根据dicttoxmldocumentation

定义自定义项名称

从版本1.7开始,如果不希望列表中的item元素被称为“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>

从文档中,我们必须使用一个函数为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 )

输出为:

^{pr2}$

相关问题 更多 >