python xml、json互轉


import xmltodict
import json
import dicttoxml

"""
XML轉化為JSON格式
安裝xmltodict
pip install xmltodict
"""


def xmlTojson():
    with open('11.xml', 'r', encoding='utf-8') as r:
        xml_str = r.read()
    # print(xml_str)
    xml_parse = xmltodict.parse(xml_str)
    print(xml_parse)
    # o = xmltodict.parse('<e> \n<a>text</a>\n <a>text</a> \n</e>')
    s = json.dumps(xml_parse)  # '{"e": {"a": ["text", "text"]}}'
    r = json.loads(s)
    with open('111.json', 'w', encoding='utf-8') as w:
        w.write(s)
    # d = r.get('root').get('item')
    # for i in d:
    #     print(i)


xmlTojson()
"""
JSON轉化為XML格式
安裝dicttoxml
pip install dicttoxml
"""


def jsonToxml():
    lis = ['張三', '李四', '王五', '趙六']
    xml_dic = []
    for i in range(len(lis)):
        dic = {
            'id': '{}'.format(i + 1),
            'name': '{}'.format(lis[i]),
        }
        xml_dic.append(dic)
    """
    使用dicttoxml轉化的xml中默認會在最外面包含一個<root> ... </root>,
    使用參數root=False可以去掉這個東西。
    同時默認的xml中還會包含每個屬性的類型,就像<item type="str">,使用參數attr_type=False可以去掉這個東西。
    """
    # xml = dicttoxml.dicttoxml(xml_dic, root=False, attr_type=False).decode('utf-8')
    xml = dicttoxml.dicttoxml(xml_dic).decode('utf-8')
    with open('111.xml', 'w', encoding='utf-8') as w:
        w.write(xml)
    print(xml)


# jsonToxml()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM