Python daily practice - the second level of data storage: the conversion of XML documents and dictionaries

The second round of interview questions:

Part 1 - Test Site:

  1. Convert the dictionary to an XML document;
  2. Convert XML documents to dictionaries.

Part 2 - Interview Questions:

1. Interview question 1: How to convert a dictionary into an XML document and save the XML document as a text file.

2. Interview question 2: How to read the content of the XML file and convert it into a dictionary.


Part 3 - Analysis:

One of the interview questions is how to convert a dictionary into an XML document and save the XML document as a text file:

  • A third-party library is needed here: dicttoxml. I need to install it~
# coding=utf-8
# _author__ = 孤寒者

import dicttoxml
from xml.dom.minidom import parseString

d = [20, 'name', {
    
    'name':'xiaohong', 'age':30, 'salary':500},
                 {
    
    'name':'honghong', 'age':34, 'salary':2050},
                 {
    
    'name':'lihua',    'age':10, 'salary':1200},
    ]

bxml = dicttoxml.dicttoxml(d, custom_root='persons')    # 注意:此时返回值是二进制类型,所以需要解码哦~
xml = bxml.decode('utf-8')
print(xml)

print("---"*25)
# 美观格式
dom = parseString(xml)
prettyxml = dom.toprettyxml(indent='  ')
print(prettyxml)

# 保存
with open('persons1.xml', 'w', encoding='utf-8') as f:
    f.write(prettyxml)

insert image description here

insert image description here

How to read the content of the XML file and convert it into a dictionary for interview question 2:

  • A third-party library is needed here: xmltodict. I need to install it~

  • The XML file for us to read is products.xml, and the content of the file is as follows:

<!-- products.xml -->
<root>
    <products>
        <product uuid='1234'>
            <id>10000</id>
            <name>苹果</name>
            <price>99999</price>
        </product>
        <product uuid='1235'>
            <id>10001</id>
            <name>小米</name>
            <price>999</price>
        </product>
        <product uuid='1236'>
            <id>10002</id>
            <name>华为</name>
            <price>9999</price>
        </product>
    </products>
</root>
# coding=utf-8
# _author__ = 孤寒者
import xmltodict

with open('products.xml', 'rt', encoding='utf-8') as f:
    xml = f.read()
    d = xmltodict.parse(xml)
    print(d)

    print("---" * 25)

    print(type(d))      # 输出为:<class 'collections.OrderedDict'>
                        # 说明此时已经转为字典(排序字典)~
    print("---"*25)
    # 美观格式
    import pprint
    dd = pprint.PrettyPrinter(indent=4)
    dd.pprint(d)

insert image description here


Part 4 - Conclusion:

Two third-party modules are required (to be installed):

  1. dicttoxml is used to convert dictionaries to XML documents;
  2. xmltodict is used to convert XML documents to dictionaries.

Guess you like

Origin blog.csdn.net/qq_44907926/article/details/123019141