XML Tutorials - Herong's Tutorial Examples - v5.25, by Herong Yang
JSON-to-XML Conversion Module for Python
This section provides a tutorial example on how to use a 'xmltodict' conversion module to perform JSON-to-XML conversions in a Python script. The output XML 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 JSON document to an XML 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, JSON-to-XML.py to use the "xmltodict" library to convert a JSON document to an XML document:
# JSON-to-XML.py # Copyright (c) 2018 HerongYang.com. All Rights Reserved. import xmltodict import json import sys file = sys.argv[1] with open(file) as input: jsonStr = input.read() obj = json.loads(jsonStr) xmlStr = xmltodict.unparse(obj) print(xmlStr)
3. Run JSON-to-XML.py to convert our JSON sample document, sample.json:
herong$ python3 JSON-to-XML.py sample.json <dictionary> <word> <update> <date>2020-01-01</date> </update> <name> <is acronym>true</is acronym> <value>DTD</value> </name> <definition>Document Type Definition</definition> <origin></origin> </word> <word> <update> <date>1000-01-01</date> </update> <name> <is acronym>false</is acronym> <value>Dog</value> </name> <definition>A domesticated carnivorous mammal</definition> <origin>docga</origin> </word> </dictionary>
As you can see, this conversion library uses almost the same conversion rules as I suggested, except that special characters in the JSON property names are not replaced. For example, "is acronym" is used as an XML element name directly, which results an invalid XML document.
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