最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【折腾】Python中xml和Json之间相互转换:xml转json,json转xml

JSON crifan 14572浏览 0评论

【背景】

看到:

python将json转换成xml

所以先去试试,用python实现,将xml转为json。

【解决过程】

1.参考:

python中将XML转换为JSON格式

所以先以:

<student>
    <stid>10213</stid>
    <info>
        <name>name</name>
        <mail>[email protected]</mail>
        <sex>male</sex>
    </info>
    <course>
        <name>math</name>
        <score>90</score>
    </course>
    <course>
        <name>english</name>
        <score>88</score>
    </course>
</student>

为例。

2.参考:

Converting XML to JSON using Python?

去试试:

xmltodict

然后去安装:

D:\tmp\dev_tools\python\xml\xml2json>pip install xmltodict

D:\tmp\dev_tools\python\xml\xml2json>

结果啥输出都没有。

所以还是手动下载对应的文件吧:

xmltodict-master.zip

解压,进去安装:

D:\tmp\dev_tools\python\xml\xml2json\xmltodict-master\xmltodict-master>setup.py install
running install
running build
running build_py
creating build
creating build\lib
copying xmltodict.py -> build\lib
running install_lib
copying build\lib\xmltodict.py -> D:\tmp\dev_install_root\Python27_x64\Lib\site-packages
byte-compiling D:\tmp\dev_install_root\Python27_x64\Lib\site-packages\xmltodict.py to xmltodict.pyc
running install_egg_info
Writing D:\tmp\dev_install_root\Python27_x64\Lib\site-packages\xmltodict-0.4.6-py2.7.egg-info

D:\tmp\dev_tools\python\xml\xml2json\xmltodict-master\xmltodict-master>

 

3.然后写测试代码去测试。

结果用:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【折腾】Python中xml和Json之间相互转换:xml转json,json转xml
https://www.crifan.com/python_convertion_between_xml_and_json

Version:    2013-05-15
Author:     Crifan
Contact:    admin (at) crifan.com
"""

import xmltodict;
import json;

def pythonXmlToJson():
    """
        demo Python xml to json
    """
    xmlStr = """"
<student>
    <stid>10213</stid>
    <info>
        <name>name</name>
        <mail>[email protected]</mail>
        <sex>male</sex>
    </info>
    <course>
        <name>math</name>
        <score>90</score>
    </course>
    <course>
        <name>english</name>
        <score>88</score>
    </course>
</student>
"""

    convertedDict = xmltodict.parse(xmlStr);
    jsonStr = json.dumps(convertedDict);
    print "jsonStr=",jsonStr;

###############################################################################
if __name__=="__main__":
    pythonXmlToJson();

却出错:

D:\tmp\tmp_dev_root\python\tutorial_summary\json_to_xml>json_to_xml.py

Traceback (most recent call last):

  File "D:\tmp\tmp_dev_root\python\tutorial_summary\json_to_xml\json_to_xml.py", line 45, in <module>

    pythonXmlToJson();

  File "D:\tmp\tmp_dev_root\python\tutorial_summary\json_to_xml\json_to_xml.py", line 39, in pythonXmlToJson

    convertedDict = xmltodict.parse(xmlStr);

  File "D:\tmp\dev_install_root\Python27_x64\lib\site-packages\xmltodict.py", line 195, in parse

    parser.Parse(xml_input, True)

xml.parsers.expat.ExpatError: unclosed token: line 1, column 0

不知道是什么原因。

4. 然后才发现,原来是把

xmlStr = """

误写成

xmlStr = """"

了,所以,要处理的xml字符串的第一个字符就是“了,所以会报错。

改为真正的:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【折腾】Python中xml和Json之间相互转换:xml转json,json转xml
https://www.crifan.com/python_convertion_between_xml_and_json

Version:    2013-05-15
Author:     Crifan
Contact:    admin (at) crifan.com
"""

import xmltodict;
import json;

def pythonXmlToJson():
    """
        demo Python xml to json
    """
    xmlStr = """
<student>
    <stid>10213</stid>
    <info>
        <name>name</name>
        <mail>[email protected]</mail>
        <sex>male</sex>
    </info>
    <course>
        <name>math</name>
        <score>90</score>
    </course>
    <course>
        <name>english</name>
        <score>88</score>
    </course>
</student>
"""

    convertedDict = xmltodict.parse(xmlStr);
    jsonStr = json.dumps(convertedDict);
    print "jsonStr=",jsonStr;

###############################################################################
if __name__=="__main__":
    pythonXmlToJson();

然后就可以正常输出了:

D:\tmp\tmp_dev_root\python\tutorial_summary\json_to_xml>json_to_xml.py

jsonStr= {"student": {"stid": "10213", "info": {"name": "name", "mail": "[email protected]", "sex": "male"}, "course": [{"name": "math", "score": "90"}, {"name": "english", "score": "88"

}]}}

5.但是很明显,没有格式化输出,很难看。

所以再去改为:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【折腾】Python中xml和Json之间相互转换:xml转json,json转xml
https://www.crifan.com/python_convertion_between_xml_and_json

Version:    2013-05-15
Author:     Crifan
Contact:    admin (at) crifan.com
"""

import xmltodict;
import json;

def pythonXmlToJson():
    """
        demo Python xml to json
    """
    xmlStr = """
<student>
    <stid>10213</stid>
    <info>
        <name>name</name>
        <mail>[email protected]</mail>
        <sex>male</sex>
    </info>
    <course>
        <name>math</name>
        <score>90</score>
    </course>
    <course>
        <name>english</name>
        <score>88</score>
    </course>
</student>
"""

    convertedDict = xmltodict.parse(xmlStr);
    jsonStr = json.dumps(convertedDict, indent=1);
    print "jsonStr=",jsonStr;

###############################################################################
if __name__=="__main__":
    pythonXmlToJson();

输出为:

D:\tmp\tmp_dev_root\python\tutorial_summary\json_to_xml>json_to_xml.py

jsonStr= {

"student": {

  "stid": "10213",

  "info": {

   "name": "name",

   "mail": "[email protected]",

   "sex": "male"

  },

  "course": [

   {

    "name": "math",

    "score": "90"

   },

   {

    "name": "english",

    "score": "88"

   }

  ]

}

}

 

6.再去试试,将json转为xml:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【折腾】Python中xml和Json之间相互转换:xml转json,json转xml
https://www.crifan.com/python_convertion_between_xml_and_json

Version:    2013-05-15
Author:     Crifan
Contact:    admin (at) crifan.com
"""

import xmltodict;
import json;

def pythonConversionXmlAndJson():
    """
        demo Python conversion between xml and json
    """
    #1.Xml to Json
    xmlStr = """
<student>
    <stid>10213</stid>
    <info>
        <name>name</name>
        <mail>[email protected]</mail>
        <sex>male</sex>
    </info>
    <course>
        <name>math</name>
        <score>90</score>
    </course>
    <course>
        <name>english</name>
        <score>88</score>
    </course>
</student>
"""

    convertedDict = xmltodict.parse(xmlStr);
    jsonStr = json.dumps(convertedDict, indent=1);
    print "jsonStr=",jsonStr;
    
    #2.Json to Xml
    dictVal = {
        'page': {
            'title': 'King Crimson',
            'ns': 0,
            'revision': {
                'id': 547909091,
            }
        }
    };
    convertedXml = xmltodict.unparse(dictVal);
    print "convertedXml=",convertedXml;

###############################################################################
if __name__=="__main__":
    pythonConversionXmlAndJson();

输出为:

D:\tmp\tmp_dev_root\python\tutorial_summary\json_to_xml>json_to_xml.py

jsonStr= {

"student": {

  "stid": "10213",

  "info": {

   "name": "name",

   "mail": "[email protected]",

   "sex": "male"

  },

  "course": [

   {

    "name": "math",

    "score": "90"

   },

   {

    "name": "english",

    "score": "88"

   }

  ]

}

}

convertedXml= <?xml version="1.0" encoding="utf-8"?>

<page><ns>0</ns><revision><id>547909091</id></revision><title>King Crimson</title></page>

 

【总结】

python中,xml和json互转的话,可以借用martinblech写的xmltodict

转载请注明:在路上 » 【折腾】Python中xml和Json之间相互转换:xml转json,json转xml

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.196 seconds, using 22.06MB memory