可以在ColdFusion Fusion 8中将XML字符串转换为JSON

|| 我处于一种情况,我收到包含XML字符串的查询。我应该将其转换为json。 我写了一个小的CF函数,它遍历/解析XML,并方便地将其转换为json。现在的问题是,XML模式已更改,这迫使我重新编写CF函数以适合新模式。 是否存在将XML转换为json的更好/通用的方法? (不过使用ColdFusion!)     
已邀请:
有XSLTJSON。 下载XSLT样式表,并将其与ColdFusion的
XmlTransform()
函数一起使用。
<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)>
    
今天可以进行此工作,必须导入当前的Saxon库并编写一个小的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();
}
    

要回复问题请先登录注册