Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách serialize Python Dictionary sang XML?

Sử dụng gói dicttoxml để chuyển đổi dictionary Python sang biểu diễn XML.

  1. Cài đặt gói: pip3 install dicttoxml
  2. Tạo dictionary: D1 = {"name": "Ravi", "age": 21, "marks": 55}
  3. Import và chuyển đổi:
    >>> from dicttoxml import dicttoxml
    >>> xml = dicttoxml(D1)
    >>> xml = xml.decode()
    >>> xml
    'Ravi2155'
  4. Lưu ra file XML:
    >>> xmlfile = open("dict.xml", "w")
    >>> xmlfile.write(xml)
    >>> xmlfile.close()