import ballerina/io;function main (string[] args) {
    var x = <xml>("<h:Store id = \"AST\" xmlns:h=\"http://www.test.com\">" +
                     "<h:name>Anne</h:name>" +
                     "<h:address><h:street>Main</h:street>" +
                     "<h:city>94</h:city></h:address>" +
                     "<h:code><h:item>4</h:item><h:item>8</h:item></h:code>" +
                     "</h:Store>");
    json j1 = x.toJSON({});
    io:println(j1);
    json j2 = x.toJSON({attributePrefix:"#", preserveNamespaces:false});
    io:println(j2);
}

XML To JSON Conversion

XML to JSON conversion can be done using the 'toJSON' function. This function takes the XML to be converted and struct of options as arguments. The options struct has two fields: attributePrefix specifies the prefix added to XML attribute/namespace keys (default is @), and preserveNamespaces specifies whether to preserve namespace prefixes during conversion.

import ballerina/io;
function main (string[] args) {
    var x = <xml>("<h:Store id = \"AST\" xmlns:h=\"http://www.test.com\">" +
                     "<h:name>Anne</h:name>" +
                     "<h:address><h:street>Main</h:street>" +
                     "<h:city>94</h:city></h:address>" +
                     "<h:code><h:item>4</h:item><h:item>8</h:item></h:code>" +
                     "</h:Store>");

Create an XML and associate it with a variable.

    json j1 = x.toJSON({});
    io:println(j1);

Convert the XML to JSON with a default attribute prefix and with namespaces.

    json j2 = x.toJSON({attributePrefix:"#", preserveNamespaces:false});
    io:println(j2);
}

Convert the XML to JSON with a custom attribute prefix and without namespaces.

$ ballerina run xml-to-json-conversion.bal
{"h:Store":{"@xmlns:h":"http://www.test.com","@id":"AST","h:name":"Anne",
"h:address":{"h:street":"Main","h:city":"94"},"h:code":{"h:item":["4","8"]}}}
{"Store":{"#id":"AST","name":"Anne","address":{"street":"Main","city":"94"},
"code":{"item":["4","8"]}}}