[英]XSLT Move child elements into new parent node
我對XSLT並不陌生,並嘗試轉換此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>
任何幫助將不勝感激,謝謝!
假設它們總是以三個為一組,您可以執行以下操作:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.