Python3 XML與字典Dict之間的相互轉化

2021-09-25 13:39:32 字數 1197 閱讀 3860

1. xml2dict包

安裝:pip install xml2dict

模組解析:通過分析其**包,可以看到,其在setup.py中設定了encoder和decoder兩個模組,安裝完成後這兩個模組會出現在你的site-packages下。因此,使用時需呼叫這兩個模組,而不是import xml2dict或import xml2dict,這是無法使用的。模組中,encoder對應xml2dict,decoder對應dict2xml。

**示例:

from encoder import xml2dict

x = xml2dict()

xml_str = "" #xml的字串,不是檔案路徑

d =x.parse(xml_str)

print(d)

1. dict2xml包

安裝:pip install dict2xml

模組解析:

**示例:

import dict2xml

from xml.dom.minidom import parsestring

def dict_to_xml(dict_in, xml_out):

xml_str = dict2xml.dict2xml(dict_in)

xml_raw = '<?xml version="1.0" encoding="utf-8"?>\n' + '\n' + xml_str + '\n'

dom = parsestring(xml.replace('\n', '')) #xml_raw中有\n換行,但不美觀

pretty = dom.toprettyxml(indent=" ", newl="\n", encoding="utf-8") #bytes

with open(xml_out, 'w') as f:

f.write(pretty.decode("utf-8"))

a = }

dict_to_xml(a, 'res.xml')

2. xml2dict包

分析:見(一、1)

from decoder import dict2xml

x = dict2xml()

d = {} #字典

t = x.parse(d)

print(t)

Python3與字典(筆記六)

字典的格式 字典名 key1 value 鍵值對,key1是鍵名,value1是對應鍵的值。每個鍵都對應乙個值,即使值為空。字典是無序的,是可變的資料型別,但字典的鍵值即key不能是可變的資料型別,如列表 字典,而且鍵是不能重複的,但是value可以重複。mas 字典的定義 print mas 輸出...

python筆記3 集合與字典

無序不重複元素的序列。可以使用大括號 或者 set 函式建立集合。注意 建立乙個空集合必須用set 而不是 是用來建立乙個空字典。usr bin python3 student print student 輸出集合,重複的元素被自動去掉 成員測試 if rose in student print r...

Python基礎知識 資料的集合之字典dict

dict全稱dictionary,在其他語言中也稱為map,使用鍵 值 key value 儲存,具有極快的查詢速度。定義格式 變數名 dic print type dic print dic 新增字典元素 通過鍵值賦值 dic 鍵值 值 dic dic major computer print d...