我想在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,我正在尝试使用写功能,但它不起作用:
with open ('filename','w') as output:
output.write(xml3)