XSLT 将子元素移动到新的父节点 [英] XSLT Move child elements into new parent node
本文介绍了XSLT 将子元素移动到新的父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 XSLT 非常陌生,正在尝试转换此 XML:
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>
对于这个预期的输出:
<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!
推荐答案
假设他们总是三人一组,你可以这样做:
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>
或更通用:
<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() < $group-size]"/>
</Employee>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这篇关于XSLT 将子元素移动到新的父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文