XSLT Move child elements into new parent node

梦想与她 提交于 2020-01-07 04:30:27

问题


I am very new to XSLT and trying to transform this XML:

<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>

To this expected output:

<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>

Any help would be greatly appreciated, thanks!


回答1:


Assuming they always come in groups of three, you could do:

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>

Or more generic:

<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>


来源:https://stackoverflow.com/questions/45515148/xslt-move-child-elements-into-new-parent-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!