日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python數(shù)據(jù)存儲之XML文檔和字典的互轉(zhuǎn)_python

作者:??孤寒者???? ? 更新時間: 2022-08-04 編程語言

考點:

  • 將字典轉(zhuǎn)換為XML文檔;
  • 將XML文檔轉(zhuǎn)換為字典。

面試題

  • 1.面試題一:如何將一個字典轉(zhuǎn)換為XML文檔,并將該XML文檔保存為文本文件。
  • 2.面試題二:如何讀取XML文件的內(nèi)容,并將其轉(zhuǎn)換為字典。

解析

如何將一個字典轉(zhuǎn)換為XML文檔,并將該XML文檔保存為文本文件:

這里需要用到第三方庫:dicttoxml。需要安裝一下

# coding=utf-8
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)

面試題二 之 如何讀取XML文件的內(nèi)容,并將其轉(zhuǎn)換為字典:

  • 這里需要用到第三方庫:xmltodict。需要安裝一下哦~
  • 供我們讀取的XML文件是products.xml,文件內(nèi)容如下:
<!-- 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
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'>
                        # 說明此時已經(jīng)轉(zhuǎn)為字典(排序字典)~
    print("---"*25)
    # 美觀格式
    import pprint
    dd = pprint.PrettyPrinter(indent=4)
    dd.pprint(d)

總結(jié)

需要兩個第三方模塊(需安裝):

  • dicttoxml用于將字典轉(zhuǎn)換為XML文檔;
  • xmltodict用于將XML文檔轉(zhuǎn)換為字典。

原文鏈接:https://juejin.cn/post/7102432915728007199

欄目分類
最近更新