Is it possible to convert an XML string to JSON in ColdFusion Fusion 8

I am in a situation where I receive a request containing an XML string. I have to convert it to json.

I wrote a small CF function that traverses / parses XML and conveniently converts it to json. Now the problem is that the XML schema has been changed, which forces me to overwrite the CF function in accordance with the new schema.

Is there a better / general way to convert XML to json? (using ColdFusion though!)

+3
source share
2 answers

There is XSLTJSON .

Download the XSLT stylesheet and use it with the ColdFusion XmlTransform()function .

<cfset xmlDoc  = XmlParse(yourXmlString, true)>

<cfset params  = StructNew()>
<cfset params["any-param"] = "you wish to pass to the XSL processor">

<cfset jsonStr = XmlTransform(xmlDoc, "xml-to-json.xsl", params)>
+5
source

, Saxon libs java.

public static String transformXML(String xmlData, String xslFile) throws SaxonApiException 
{

    StringWriter sw = new StringWriter();
    XdmNode source = null;

    Processor proc = new Processor(false);
    XsltCompiler comp = proc.newXsltCompiler();
    XsltExecutable exp = comp.compile(new StreamSource(new File(xslFile)));

    try
    {
        source = proc.newDocumentBuilder().build(new StreamSource(new ByteArrayInputStream(xmlData.getBytes("UTF-8"))));
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Serializer out = proc.newSerializer(sw);
    //out.setOutputProperty(Serializer.Property.METHOD, "html");
    out.setOutputProperty(Serializer.Property.INDENT, "yes");
    XsltTransformer trans = exp.load();
    trans.setInitialContextNode(source);
    trans.setDestination(out);
    trans.transform();

    return sw.toString();
}
+1

All Articles