2017-08-04 129 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