Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何将一个字典转换为XML文档,并将该XML文档保存成文本文件 #69

Open
Sogrey opened this issue Feb 17, 2020 · 0 comments
Labels
数据存储 文件存储,数据库存储
Projects

Comments

@Sogrey
Copy link
Owner

Sogrey commented Feb 17, 2020

'''
dicttoxml
pip install dicttoxml
pip install xmltodict


'''

import dicttoxml
import os
from xml.dom.minidom import parseString

d = [20,'names',{'name':'Bill','age':30,'salary':2000},
                {'name':'Mike','age':40,'salary':3000},
                {'name': 'John', 'age': 20, 'salary': 1000}]

bxml = dicttoxml.dicttoxml(d,custom_root='persons')
xml = bxml.decode('utf-8')
print(xml)
dom = parseString(xml) ## string 转 xml
prettyxml = dom.toprettyxml(indent='  ') ## 设置缩进
print(prettyxml)

f = open('files/persons1.xml','w',encoding='utf-8')
f.write(prettyxml)
f.close()
<?xml version="1.0" ?>
<persons>
  <item type="int">20</item>
  <item type="str">names</item>
  <item type="dict">
    <name type="str">Bill</name>
    <age type="int">30</age>
    <salary type="int">2000</salary>
  </item>
  <item type="dict">
    <name type="str">Mike</name>
    <age type="int">40</age>
    <salary type="int">3000</salary>
  </item>
  <item type="dict">
    <name type="str">John</name>
    <age type="int">20</age>
    <salary type="int">1000</salary>
  </item>
</persons>

需要2个第三方模块(需要安装)

  • dicttoxml用于将字典转换为XML文档
  • xmltodict用于将XML文档转换为字典
@Sogrey Sogrey added the 数据存储 文件存储,数据库存储 label Feb 17, 2020
@Sogrey Sogrey added this to 数据存储 in Python QAs Feb 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数据存储 文件存储,数据库存储
Projects
Python QAs
数据存储
Development

No branches or pull requests

1 participant