![](/img/trans.png)
[英]xslt 1.0- Using xslt 1.0 how can I make the xslt work for multiple document elements
[英]Merge specific elements but keep document order using XSLT 1.0
給定以下文件:
<doc>
<a>a</a>
<b>1</b>
<b>2</b>
<b>3</b>
<c>c</c>
</doc>
我希望將其轉換為:
<doc>
<a>a</a>
<b>1,2,3</b>
<c>c</c>
</doc>
到目前為止,我所擁有的(大部分來自SO上的另一篇文章):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="doc">
<xsl:copy>
<xsl:apply-templates select="*[not(self::b)]"/>
<b><xsl:apply-templates select="b/text()"/></b>
</xsl:copy>
</xsl:template>
<xsl:template match="b/text()">
<xsl:if test="position() > 1">,</xsl:if>
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>
這將產生以下結果:
<doc><a>a</a><c>c</c><b>1,2,3</b></doc>
但是,我一直在努力尋找一種可以保持文檔順序完整的解決方案。 任何<b>
元素運行都應替換為包含原始元素文本(以逗號分隔的列表)的單個元素。 其他元素不應重新排序。
為什么不簡單地做:
<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:template match="/doc">
<xsl:copy>
<xsl:copy-of select="a"/>
<b>
<xsl:for-each select="b">
<xsl:value-of select="."/>
<xsl:if test="position() !=last()">,</xsl:if>
</xsl:for-each>
</b>
<xsl:copy-of select="c"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
假設您知道傳入XML的結構,並且可以分別枚舉b
之前和之后的元素。 否則,您將必須執行以下操作:
<xsl:template match="/doc">
<xsl:copy>
<xsl:apply-templates select="*[not(self::b or preceding-sibling::b)]"/>
<b>
<xsl:for-each select="b">
<xsl:value-of select="."/>
<xsl:if test="position() !=last()">,</xsl:if>
</xsl:for-each>
</b>
<xsl:apply-templates select="*[not(self::b or following-sibling::b)]"/>
</xsl:copy>
</xsl:template>
您可以在其他模式下使用同級遞歸:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="b[not(preceding-sibling::*[1][self::b])]">
<xsl:copy>
<xsl:apply-templates select="." mode="merge"/>
</xsl:copy>
</xsl:template>
<xsl:template match="b[preceding-sibling::*[1][self::b]]"/>
<xsl:template match="b" mode="merge">
<xsl:value-of select="."/>
<xsl:variable name="next" select="following-sibling::*[1][self::b]"/>
<xsl:if test="$next">
<xsl:text>,</xsl:text>
<xsl:apply-templates select="$next" mode="merge"/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.