XML Tutorials - Herong's Tutorial Examples - v5.25, by Herong Yang
XML-to-JSON Conversion Module for Python
This section provides a tutorial example on how to use a 'xmltodict' conversion module to perform XML-to-JSON conversions in a Python script. The output JSON document is good, only if input XML document contains well structured data.
If you are familiar with Python language, you can try to use the "xmltodict" module to convert your XML document to a JSON document.
1. Install "xmltodict" module, if it's not done yet.
herong$ pip3 install xmltodict Collecting xmltodict Installing collected packages: xmltodict Successfully installed xmltodict-0.12.0
2. Create a Python script, XML-to-JSON.py to use the "xmltodict" library to convert an XML document to a JSON document:
# XML-to-JSON.py # Copyright (c) 2018 HerongYang.com. All Rights Reserved. import xmltodict import json import sys file = sys.argv[1] with open(file) as input: xmlStr = input.read() obj = xmltodict.parse(xmlStr) jsonStr = json.dumps(obj,indent=' ') print(jsonStr)
3. Run XML-to-JSON.py to convert our XML sample document, xml.html:
herong$ python3 XML-to-JSON.py xml.html { "html": { "body": { "@bgcolor": "#dddddd", "h4": "My XML Web Page", "p": [ "A simple text paragraph.", { "em": "highlight text", "br": null, "font": { "@color": "#ff0000", "@size": "+1", "#text": "font changes" }, "#text": "A complex paragraph with , line breaks,\n\t, etc." } ] } } }
As you can see, this conversion library also uses similar conversion rules. The conversion is reversible, only if the XML document contains well structured data like products.xml used in the previous tutorial.
Table of Contents
Introduction of XML (eXtensible Markup Language)
What Is JSON (JavaScript Object Notation)
Convert XML Document to JSON Document
XML-to-JSON Conversion Tool at onlinexmltools.com
XML-to-JSON Conversion Library for Java
►XML-to-JSON Conversion Module for Python
Convert JSON Document to XML Document
JSON-to-XML Conversion Tool at onlinexmltools.com
JSON-to-XML Conversion Library for Java
JSON-to-XML Conversion Module for Python
DOM (Document Object Model) Programming Interface
SAX (Simple API for XML) Programming Interface
DTD (Document Type Definition) Introduction
Validating an XML Document against the Specified DTD Document Type
XSD (XML Schema Definition) Introduction
Validating XML Documents Against Specified XML Schemas
XSL (Extensible Stylesheet Language) Introduction
XSLT (XSL Transformations) Introduction
XSLT Elements as Programming Statements
Control and Generate XML Element in the Result
PHP Extensions for XML Manipulation
Processing XML with Python Scripts
XML Tools Plugin for Notepad++
XML Plugin Packages for Atom Editor