2017年11月8日 星期三

Python - Convert a dict to XML in python - 將字典轉換為XML的格式

版本

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Codes:

# dict to xml
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import tostring
def dict_to_xml(tag, d):
    ele = Element(tag)
    for key, val in d.items():
        child = Element('key',{'name':key})
        child.text = str(val)
        ele.append(child)
    return ele

dic1 = {'a':5,'123b':22,'c':'str1'}
print(dic1)
print('-'*85)
xml_str = tostring(dict_to_xml('score', dic1)  )
xml_str2 = xml_str.decode()
print(xml_str2)
print('='*85)
xml_str = tostring(dict_to_xml('score', dic1), encoding='utf8', method='xml')
xml_str2 = xml_str.decode()
print(xml_str2)

執行結果:

沒有留言:

張貼留言