2012-09-17 49 views
1

即使使用本網站上的所有優秀技巧,我仍然遇到一些xslt問題。我很新。我有這個源文件:排序並將元素移動到新元素中

<?xml version="1.0" encoding="utf-8"?> 
<file> 
    <id>1</id> 
    <row type="A"> 
    <name>ABC</name> 
    </row> 
    <row type="B"> 
    <name>BCA</name> 
    </row> 
    <row type="A"> 
    <name>CBA</name> 
    </row> 
</file> 

,我想添加元素和類型對行進行排序,得到這個結果

<file> 
    <id>1</id> 
    <details> 
    <row type="A"> 
    <name>ABC</name> 
    </row> 
    <row type="A"> 
     <name>CBA</name> 
    </row> 
    <row type="B"> 
    <name>BCA</name> 
    </row> 
    </details> 
</file> 

我能夠使用此行來排序:

<xsl:template match="file"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*/row"/> 
     <xsl:apply-templates> 
     <xsl:sort select="@type" data-type="text"/> 
     </xsl:apply-templates> 
    </xsl:copy> 
    </xsl:template> 

,我能夠用這個

<xsl:template match="file"> 
    <xsl:copy> 
     <xsl:copy-of select="@*" /> 
     <xsl:apply-templates select="*[not(name(.)='row')]" /> 
     <details> 
     <xsl:apply-templates select="row" /> 
     </details> 
    </xsl:copy> 
    </xsl:template> 
移動行

但我無法在嘗試合併它們時產生正確的答案。希望我瞭解更多XSLT,當我看到如何組合。由於我正在創建一個新元素<details>,我認爲在創建新的<details>元素之前必須完成排序。我必須使用xslt 1.0。

回答

0

像這樣的事情似乎工作:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="file"> 
    <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:copy-of select="row[1]/preceding-sibling::*" /> 
     <details> 
     <xsl:for-each select="row"> 
      <xsl:sort select="@type" data-type="text"/> 
      <xsl:copy-of select="."/> 
     </xsl:for-each> 
     </details> 
     <xsl:copy-of select="row[last()]/following-sibling::*" /> 
    </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

這是我得到的結果是:

<?xml version="1.0" encoding="utf-8"?> 
<file> 
    <id>1</id> 
    <details> 
    <row type="A"> 
     <name>ABC</name> 
    </row> 
    <row type="A"> 
     <name>CBA</name> 
    </row> 
    <row type="B"> 
     <name>BCA</name> 
    </row> 
    </details> 
</file> 
+0

謝謝!它工作正常,我理解你的解決方案:)很容易在其他文件上重複使用。 – user1663498