有時我們想看下系統生成的XML文件(如XML格式的Project文件),如果文件結構簡單,我們浏覽器看起來還比較方便,但是隨著XML schema復雜後就變得讓人頭疼啦,單獨寫一個程序去做展現又有點小題大做。這時XSL就用體現它的價值啦,當然XSL不只是為了顯示,更多的目的是從一個格式生成另個一格式的XML或者其他格式的文件。本文只說說格式化。
參看XLT格式化XML那點事(二)
<xsl:template match=”/”> </xsl:template>
如下示例,選擇了pets下面的子元素,並循環顯示子元素的幾點名字:
<xsl:for-each select=”/pets/*”> <xsl:value-of select=”name()”/> </xsl:for-each>
<xsl:if test=”@weight < 10”> <i>its weight is less than 10 km</i> </xsl:if>
<xsl:choose > <xsl:when test=”name() = ‘pig’”> <i>this is a pig</i> </xsl:when> <xsl:otherwise> <i>this is not a pig</i> </xsl:otherwise> </xsl:choose>
選擇子節點price
<xsl:value-of select=”pets/*/price”/>
選擇屬性weight
<xsl:value-of select=”pets/*/@weight”/>
用來向節點添加屬性,例如:
<font> <xsl:attribute name=”color”><xsl:value-of select=”pets/*/@color”/></xsl:attribute> </font>
將輸出<font color=”red”></font>
如果xml文件結構比較復雜,可以定義多個template,然後使用<xsl:apply-templates>標簽應用模板,xsl:apply-templates 可以指定屬性select=”xpath”來選擇應用的模板,或者不指定select表示選擇當前節點的模板。
<?xml-stylesheet type="text/xsl" href="icoreNested.xsl"?>
參考Can Chrome be made to perform an XSL transform on a local file
<html> <head> <script> function loadXMLDoc(filename) { var progressBar = document.getElementById("p"); if (window.ActiveXObject) { xhttp = new ActiveXObject("Msxml2.XMLHTTP"); } else { xhttp = new XMLHttpRequest(); } xhttp.open("GET", filename, false);//Synchronous loadXMLDoc try { xhttp.onprogress = function(pe) { if(pe.lengthComputable) { progressBar.max = pe.total progressBar.value = pe.loaded } } xhttp.onloadend = function(pe) { progressBar.value = pe.loaded } } catch(err) {} // Helping IE11 xhttp.send(); return xhttp.responseXML; } function displayResult() { xml = loadXMLDoc("cdcatalog.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> </head> <body onload="displayResult()"> <h2>Content as Follow:</h2> <progress id=p ></progress> <div id="example" /> </body> </html>
源碼下載
Can Chrome be made to perform an XSL transform on a local file?
嵌套的可折疊塊