鉴于XML:
<root>
<txto>Header text<txto>
<txt>more paragraph text</txt>
<txt>even more paragraph text</txt>
<txto>Another header<txto>
<txt> … </txt>
<txt> … </txt>
</root>
所需的输出是让第一个标头定义一个节,而保留第二个标头:
<root>
<n1>
<o>Header text</o>
<txt>more paragraph text</txt>
<txt>even more paragraph text</txt>
</n1>
<txto>Another header<txto>
<txt> … </txt>
<txt> … </txt>
</root>
使用XSL:
<xsl:template match=“//txto[starts-with(., ‘Header’)]”>
<n1>
<o><xsl:value-of select="."/></o>
<xsl:apply-templates select="following-sibling::txt" />
</n1>
</xsl:template>
但是,结果是txt元素“重复”:
<root>
<n1>
<o>Header text</o>
<txt>more paragraph text</txt>
<txt>even more paragraph text</txt>
</n1>
<txt>more paragraph text</txt> <-- 'duplicated'
<txt>even more paragraph text</txt> <-- 'duplicated'
<txto>Another header<txto>
<txt> … </txt>
<txt> … </txt>
</root>
这可能与已经将所有txt节点复制到结果树的Identity转换有关:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
如何避免将两个“重复的” txt节点复制到结果树?我只希望它们在n1节点内,而不是紧随其后。
在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:key name="following-txt" match="txt" use="generate-id(preceding-sibling::txto[1])" />
<xsl:template match="/root">
<xsl:copy>
<xsl:apply-templates select="txto"/>
</xsl:copy>
</xsl:template>
<xsl:template match="txto[starts-with(., 'Header')]">
<n1>
<o>
<xsl:value-of select="." />
</o>
<xsl:copy-of select="key('following-txt', generate-id())"/>
</n1>
</xsl:template>
<xsl:template match="txto">
<xsl:copy-of select=". | key('following-txt', generate-id())"/>
</xsl:template>
</xsl:stylesheet>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句