如何在xslt转换中模块化一组重复的输出?例如,我有类似下面的代码(伪代码)。
<foreach "path">
<if "count(/subPath) = 0">
<a><value-of "x"/></a>
<b><value-of "y"/></b>
<c></c>
</fi>
<else>
<foreach "subPath">
<a><value-of "../x"/></a>
<b><value-of "../y"/></b>
<c><value-of "z"/></c>
</foreach>
</else>
</foreach>并希望如下所示:
<foreach "path">
<if "count(/subPath) = 0">
<?/>
</fi>
<else>
<foreach "subPath">
<?/>
</foreach>
</else>
</foreach>
<?>
<a><value-of "../x"/></a>
<b><value-of "../y"/></b>
<c><value-of "z"/></c>
</?>我要寻找的是什么结构?
发布于 2011-12-31 00:50:57
I.伪码翻译
您的伪代码将1:1转换为这个XSLT转换
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:for-each select="/t/m/n/p">
<xsl:choose>
<xsl:when test="not(subPath)">
<a><xsl:value-of select="x"/></a>
<b><xsl:value-of select="y"/></b>
</xsl:when>
<xsl:otherwise>
<xsl:for-each select="subPath">
<a><xsl:value-of select="../x"/></a>
<b><xsl:value-of select="../y"/></b>
<c><xsl:value-of select="z"/></c>
</xsl:for-each>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>在此XML文档上应用时(问题中未提供此类文档!):
<t>
<m>
<n>
<p>
<x>1</x>
<y>2</y>
<subPath>
<z>3</z>
</subPath>
<subPath>
<z>4</z>
</subPath>
</p>
</n>
</m>
</t>生成所需的正确结果
<a>1</a>
<b>2</b>
<c>3</c>
<a>1</a>
<b>2</b>
<c>4</c>II.重构
这是一个重构后的等价转换,它不使用任何 xsl:for-each 或任何显式条件指令
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="p[not(subPath)]" name="processP">
<xsl:param name="pNode" select="."/>
<a><xsl:value-of select="$pNode/x"/></a>
<b><xsl:value-of select="$pNode/y"/></b>
</xsl:template>
<xsl:template match="p/subPath">
<xsl:call-template name="processP">
<xsl:with-param name="pNode" select=".."/>
</xsl:call-template>
<c><xsl:value-of select="z"/></c>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>当应用于相同的文档时(如上),同样会产生相同的正确结果
<a>1</a>
<b>2</b>
<c>3</c>
<a>1</a>
<b>2</b>
<c>4</c>注意到
发布于 2011-12-30 23:52:45
您可能正在寻找named templates。
发布于 2011-12-30 23:52:59
您正在寻找可以用<call-template>调用的模板(<template>)。有关详细信息,请访问http://www.w3.org/TR/xslt#named-templates。
https://stackoverflow.com/questions/8681250
复制相似问题