ใช้แพ็กเกจ dicttoxml เพื่อแปลง Python Dictionary เป็น XML representation
เริ่มต้นด้วยการติดตั้งแพ็กเกจ dicttoxml
pip3 install dicttoxml
สร้าง Dictionary object
>> D1 = {"name": "Ravi", "age": 21, "marks": 55}
นำเข้าฟังก์ชัน dicttoxml() จากแพ็กเกจ dicttoxml และใช้ D1 เป็นอาร์กิวเมนต์ ฟังก์ชันจะคืนค่า encoded string เป็น XML representation ของ Dictionary
>> from dicttoxml import dicttoxml
>>> xml = dicttoxml(D1)
ได้ decoded string ด้วยฟังก์ชัน decode()
สตริงที่ได้จะมี XML version ของ Dictionary
>> xml = xml.decode()
>>> xml
'Ravi 21 55 '
สามารถจัดเก็บไว้ในไฟล์ XML ได้อีกด้วย
>> xmlfile = open("dict.xml", "w")
>>> xmlfile.write(xml)
>>> xmlfile.close()