Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้าง XML ด้วย Python

เพื่อสร้าง XML จาก dictionary ใน Python คุณต้องติดตั้งแพ็กเกจ dicttoxml สามารถติดตั้งได้ด้วยคำสั่ง

$ pip install dicttoxml

หลังจากติดตั้งแล้ว สามารถใช้เมธอด dicttoxml เพื่อสร้าง XML ได้

ตัวอย่าง

a = {
    'foo': 45,
    'bar': {
        'baz': "Hello"
    }
}
xml = dicttoxml.dicttoxml(a)
print(xml)

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้

b'45Hello'

คุณยังสามารถจัดรูปแบบเอาต์พุทให้อ่านง่ายด้วยเมธอด toprettyxml

ตัวอย่าง

from xml.dom.minidom import parseString
a = {
    'foo': 45,
    'bar': {
        'baz': "Hello"
    }
}
xml = dicttoxml.dicttoxml(a)
dom = parseString(xml)
print(dom.toprettyxml())

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้

<?xml version = "1.0" ?>
<root>
  <foo type = "int">45</foo>
  <bar type = "dict">
    <baz type = "str">Hello</baz>
  </bar>
</root>