我想在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)
根据dicttoxmldocumentation:
定义自定义项名称
从版本1.7开始,如果不希望列表中的item元素被称为“item”,可以使用一个以父元素名称(即列表名称)为参数的函数来指定元素名称。在
从文档中,我们必须使用一个函数为xml提供自定义密钥名。在
引用-dicttoxml github
输出为:
^{pr2}$相关问题 更多 >
编程相关推荐