XSD-aware XML-to-JSON Conversion

XSD-Aware XML-to-JSON Conversion

Converting XML to JSON is often imperfect; for example, converting elements marked as repeatable in the XSD should always be converted to a JSON array; however, without schema information, an array is generated only if two or more instances of the element occur in the XML. Other issues relate to numeric, or Boolean data which is typically converted to string instead of using a corresponding JSON type.


Consider this XSD:

<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="item" minOccurs="0" maxOccurs="unbounded" type="xsd:int"/>
                <xsd:element name="boolean" type="xsd:boolean" minOccurs="0"/>                
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

This is a valid sample XML:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<root xmlns="http://tempuri.org/XMLSchema.xsd">
    <item>1</item>
    <boolean>1</boolean>
</root>

A typical XML-to-JSON conversion will result in a JSON such as this:

{
  "item": "1",
  "boolean": "1"
}

The generated JSON exhibits three issues:

  • item should have been an array
  • The value of an item should be a numeric value (i.e. without quotes)
  • boolean should have been true

A more intuitive conversion would generate the following JSON:

{
    "item": [
        1
    ],
    "boolean": true
}

QTAssistant can handle the above XSD features in its built-in XSD-aware, XML-to-JSON conversion. In order to work, the XML file must be XSD 1.0 valid. Use the Properties tool window to associate an XSD 1.0 with the XML file. The Conversion To JSON command is available in the XML ribbon page.