2011-04-08 49 views
1

我是XSLT的新手,雖然我已經成功地完成了許多任務,但到目前爲止......排序讓我很難。對XML文件的節點進行排序

我需要一個小例子的幫助,以便我能更好地理解xsl:sort。

我的XML數據看起來如下:

<NewTerms> 
    <newTerm>Zebra</newTerm> 
    <newTerm>Horse</newTerm> 
    <newTerm>Cat</newTerm> 
    <newTerm>Lion</newTerm> 
    <newTerm>Jaguar</newTerm> 
    <newTerm>Cheetah</newTerm> 
    <newTerm>Deer</newTerm> 
    <newTerm>Buffalo</newTerm> 
    <newTerm>Dog</newTerm> 
</NewTerms> 

,我只是單純的想按字母順序從一個XSL表進行排序。 (這是不工作&)我寫的XSL是如下:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

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

    <xsl:template match="NewTerms"> 

     <xsl:apply-templates> 
     <xsl:sort select="newTerm"/> 
     </xsl:apply-templates> 

    </xsl:template> 

</xsl:stylesheet> 

我非常肯定,我還沒有明白怎麼的xsl:排序功能。如果你幫助我通過這個小例子...我想我會更好地理解它。

謝謝。

茉莉

回答

5

我想你,因爲在你的<xsl:output>的方法是「XML」又要有效的XML結構作爲輸出。 你可以試試這個:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" 
version="1.0"> 

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

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

</xsl:stylesheet> 

這給出了這樣的輸出:

<?xml version="1.0" encoding="UTF-8"?> 
<NewTerms> 
<newTerm>Buffalo</newTerm> 
<newTerm>Cat</newTerm> 
<newTerm>Cheetah</newTerm> 
<newTerm>Deer</newTerm> 
<newTerm>Dog</newTerm> 
<newTerm>Horse</newTerm> 
<newTerm>Jaguar</newTerm> 
<newTerm>Lion</newTerm> 
<newTerm>Zebra</newTerm> 
</NewTerms> 

是否幫助你嗎?

你也可以看看排序的定義,如: http://www.w3schools.com/xsl/el_sort.asp http://www.w3.org/TR/xslt#sorting

最好的問候, 彼得

+0

謝謝你非常非常......有時候有一個具體的例子有助於理解比讀理論概念更....所以,再次感謝您:) .. 。你是對的,我正在處理一個.xml輸出。週末愉快! – Jasmin 2011-04-08 12:31:24

+0

您能解釋一下爲什麼我們應該使用「@ * | node()」...因爲我的印象是我應該直接命名我想排序的節點名稱。當然我錯了,但想知道爲什麼? – Jasmin 2011-04-08 12:43:28

+0

@Jasmin:你所做的只是複製整個XML結構,然後添加xsl:sort元素。這種複製機制被稱爲「身份變換」。請看看:http://www.w3.org/TR/xslt#copying這是非常有用的。 – Peter 2011-04-08 13:26:06

2
<xsl:template match="NewTerms"> 
<xsl:apply-templates> 
    <xsl:sort select="newTerm"/> 
</xsl:apply-templates> 
</xsl:template> 

我非常肯定,我沒有 瞭解如何XSL:排序功能

你說得對。從http://www.w3.org/TR/xslt#sorting

xsl:sort具有select屬性 ,其值是一個表達式。 對於要處理的每個 節點,表達式 與該節點作爲當前 節點和節點的完整列表 在 未排序順序爲當前節點 列表被處理評價。*生成的對象是 轉換爲字符串,就好像通過調用 到string函數;此 字符串用作 該節點的排序關鍵字。 select屬性的默認值爲.,這將使 導致當前的 節點的字符串值用作排序關鍵字。

*重點是我的。

你想:

<xsl:template match="NewTerms"> 
<xsl:apply-templates> 
    <xsl:sort/> 
</xsl:apply-templates> 
</xsl:template> 
+0

+1,用於解釋OP代碼中的問題。 – 2011-04-08 13:20:21

+0

+1謝謝你的確切解釋。我剛剛提供了一個解決方案,以原始代碼。 – Peter 2011-04-08 13:32:51

相關問題