2010-12-22 47 views
0

我想與N段將文件轉換這種格式:合併同類數據的XML節點中的屬性關鍵(XSL)

<File> 
     <Sections Section="Section1" fieldName="field1" fieldValue="value1"/> 
     <Sections Section="Section1" fieldName="field2" fieldValue="value2"/> 
     <Sections Section="Section1" fieldName="field3" fieldValue="value3"/> 
     <Sections Section="Section2" fieldName="field1" fieldValue="value1"/> 
     <Sections Section="Section2" fieldName="field2" fieldValue="value2"/> 
     <Sections Section="Section2" fieldName="field3" fieldValue="value3"/> 
</File> 

進入

<File> 
    <Section1 field1="value1" field2="value2" field3="value3"/> 
    <Section2 field1="value1" field2="value2" field3="value3"/> 
</File> 

使用屬性部分的價值爲重點創造元素。

我嘗試了一些東西,但我不能。

你能幫我嗎?

謝謝。

+0

XSLT版本1或2? – 2010-12-22 16:35:00

回答

2

這裏是一個XSLT 1.0樣式:

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

    <xsl:output indent="yes"/> 

    <xsl:key name="k1" match="File/Sections" use="@Section"/> 

    <xsl:template match="File"> 
    <xsl:copy> 
     <xsl:apply-templates select="Sections[generate-id() = generate-id(key('k1', @Section)[1])]" mode="group"/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="Sections" mode="group"> 
    <xsl:element name="{@Section}"> 
     <xsl:apply-templates select="key('k1', @Section)"/> 
    </xsl:element> 
    </xsl:template> 

    <xsl:template match="Sections"> 
    <xsl:attribute name="{@fieldName}"> 
     <xsl:value-of select="@fieldValue"/> 
    </xsl:attribute> 
    </xsl:template> 

</xsl:stylesheet> 
1

而這裏的XSLT 2.0樣式表

<xsl:stylesheet version="2.0" 
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/File" > 
     <xsl:copy> 
     <xsl:for-each-group select="Sections" group-by="@Section"> 
      <xsl:element name="{current-grouping-key()}"> 
       <xsl:for-each select="current-group()"> 
        <xsl:attribute name="{@fieldName}" select="@fieldValue"/> 
       </xsl:for-each> 
      </xsl:element> 
     </xsl:for-each-group> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet>