2013-08-28 55 views
1

在JavaScript中,嘗試轉換動態創建的XML數據島,使用XSL文件對其進行排序,但結果是排序後的數據全部在一行上,沒有XML格式或正確縮進。它看起來沒有被使用。我需要在生成的transformNode()中生成XML標記和縮進。JavaScript處理XSL文件不起作用

JavaScript代碼:

var sourceXML = document.getElementById(XMLViewID); //textArea containing XML 
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); 
xmlDoc.async = false; 
xmlDoc.loadXML(sourceXML.value); 

var xslDoc = new ActiveXObject("Microsoft.XMLDOM"); 
xslDoc.async=false; 
xslDoc.load("xsl.xsl"); 

// This should be the sorted, formatted XML data, in tree and indented format? 
var sorted = xmlDoc.transformNode(xslDoc); 

XML數據:

<table> 
    <row> 
     <A>j</A> 
     <B>0</B> 
    </row> 
    <row> 
     <A>c</A> 
     <B>4</B> 
    </row> 
    <row> 
     <A>f</A> 
     <B>6</B> 
    </row> 
</table> 

xsl.xsl:

<xsl:output method="xml" indent="yes" omit-xml-declaration="no"/> 

<xsl:template match="/"> 
    <xsl:apply-templates select="table/row"> 
     <xsl:sort select="A" order="ascending"/> 
    </xsl:apply-templates> 
</xsl:template> 

<xsl:template match="row"> 
    <xsl:value-of select="A"/> 
    <xsl:value-of select="B"/> 
</xsl:template> 

我想用「縮進= yes」和「省略的XML聲明=不」所產生的改造應與縮進和格式:

<?xml version="1.0" encoding="UTF-16"?> 
    <table> 
     <row> 
     <tr> 
      <A>j</A> 
      <B>0</B> 
     </tr> 
     <tr> 
      <A>c</A> 
      <B>4</B> 
     </tr> 
     <tr> 
      <A>f</A> 
      <B>6</B> 
     </tr> 
     </row> 
    </table> 

但取而代之的則是:在同一行c4f6j0,無格式,沒有XML標籤...

回答

1

到目前爲止,您的XSLT產生無非是文本節點,如果你想與XML元素,那麼你需要的代碼創建它們像

<xsl:template match="table"> 
    <xsl:copy> 
    <xsl:apply-templates select="row"> 
     <xsl:sort select="A"/> 
    </xsl:apply-templates> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
</xsl:template> 
+0

與之相匹配的模板=」 @ * | node()是標識轉換。它確保未在其他模板中提及的節點和屬性按原樣複製。 [更多](http://cnx.org/content/m43518/latest/) –

+1

這很好地讓xml標籤在那裏。我想我已經知道我的下一個問題的答案,但是有沒有辦法讓縮進的格式也放入已排序的字符串中?我得到的結果是預期的一切,但沒有縮進。我的猜測是,這取決於顯示結果xml的內容,但如果有一種方法可以讓xslt自動添加,那就太好了。 – Andy

+0

試着找出http://stackoverflow.com/search?q=[xslt]+white+space+preserve的答案。 –