2017-08-04 78 views
0

我很新的XSLT,並試圖改變這個XML:XSLT移動子元素到新的父節點

<Company> 
    <Employee> 
     <name>Jane</name> 
     <id>200</id> 
     <title>Dir</title> 
     <name>Joe</name> 
     <id>100</id> 
     <title>Mgr</title> 
     <name>Sue</name> 
     <id>300</id> 
     <title>Analyst</title> 
    </Employee> 
</Company> 

爲了期望的輸出:

<Company> 
    <Employee> 
     <name>Jane</name> 
     <id>200</id> 
     <title>Dir</title> 
    </Employee> 
    <Employee> 
     <name>Joe</name> 
     <id>100</id> 
     <title>Mgr</title> 
    </Employee> 
    <Employee> 
     <name>Sue</name> 
     <id>300</id> 
     <title>Analyst</title> 
    </Employee> 
</Company> 

任何幫助將不勝感激,謝謝!

+0

可以假設均勻的結構{名稱; ID;標題}? –

回答

0

假設他們總是三個一組,你可以這樣做:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="/Company"> 
    <xsl:copy> 
     <xsl:for-each select="Employee/name"> 
      <Employee> 
       <xsl:copy-of select=". | following-sibling::id[1] | following-sibling::title[1]"/> 
      </Employee> 
     </xsl:for-each> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

或多個通用:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:param name="group-size" select="3" /> 

<xsl:template match="/Company"> 
    <xsl:copy> 
     <xsl:for-each select="Employee/*[position() mod $group-size = 1]"> 
      <Employee> 
       <xsl:copy-of select=". | following-sibling::*[position() &lt; $group-size]"/> 
      </Employee> 
     </xsl:for-each> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 
+0

對不起,我剛纔有機會迴應。在原始XML中,它們總是以三個一組的形式出現。我在樣式表中試過了你的建議,它工作。謝謝! – James