XSLT on the Client and Server

1.XSLT on the Client

@RequestMapping(value = "/XSLTClient")
public String XSLTClient() {
    return "XSLTOnClient";
}
<!-- XSLTOnClient.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script>
        function loadXMLDoc(filename)
        {
            if (window.ActiveXObject)
            {
                xhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            else
            {
                xhttp = new XMLHttpRequest();
            }
            xhttp.open("GET", filename, false);
            try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
            xhttp.send("");
            return xhttp.responseXML;
        }

        function displayResult()
        {
            // "[[@{cdcatalog_client.xml}]]"这里使用了Thymeleaf模板引擎的语法。
            xml = loadXMLDoc("[[@{cdcatalog_client.xml}]]");
            xsl = loadXMLDoc("[[@{cdcatalog.xsl}]]");
            // code for IE
            if (window.ActiveXObject || xhttp.responseType == "msxml-document")
            {
                ex = xml.transformNode(xsl);
                document.getElementById("example").innerHTML = ex;
            }
            // code for Chrome, Firefox, Opera, etc.
            else if (document.implementation && document.implementation.createDocument)
            {
                xsltProcessor = new XSLTProcessor();
                xsltProcessor.importStylesheet(xsl);
                resultDocument = xsltProcessor.transformToFragment(xml, document);
                document.getElementById("example").appendChild(resultDocument);
            }
        }
    </script>
    <title>XSLT on the Client</title>
</head>
<body onload="displayResult()">
<div id="example"></div>
</body>
</html>

2.XSLT on the Server

@RequestMapping("/XSLTServer")
public String XSLTServer() throws TransformerException, IOException {
    Source xslt = new StreamSource(new ClassPathResource("static/cdcatalog.xsl").getFile());
    Source text = new StreamSource(new ClassPathResource("static/cdcatalog_client.xml").getFile());
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xslt);

    transformer.transform(text, new StreamResult(new File("cdcatalog.html")));
    return "XSLTOnClient";
}



注:w3schools官网的示例用的是PHP和ASP,都可以直接返回XML通过XSLT转换后的HTML。

参考:

posted @ 2020-08-21 11:58  gzhjj  阅读(109)  评论(0编辑  收藏  举报