Xslt 基于存储在另一个元素中的键选择XML元素
不熟悉xsl,如果这是一个常见问题,我很抱歉- 我有一些xml,看起来像是简化了的示例,但这是我用来处理的:Xslt 基于存储在另一个元素中的键选择XML元素,xslt,xslt-1.0,Xslt,Xslt 1.0,不熟悉xsl,如果这是一个常见问题,我很抱歉- 我有一些xml,看起来像是简化了的示例,但这是我用来处理的: <root> <items> <item> <value>1</value> <id>1</id> </item> <item> <value>2</value> <id>
<root>
<items>
<item>
<value>1</value>
<id>1</id>
</item>
<item>
<value>2</value>
<id>2</id>
</item>
<item>
<value>99</value>
<id>3</id>
</item>
</items>
<itemList>
<id>1</id>
<id>2</id>
</itemList>
</root>
我是从.Net XslCompiledTransform运行这个程序的,如果相关的话。我不知道这会让我感觉更聪明还是更愚蠢,但我在问题底部发布的猜测在我把它扔到xsl中时,实际上似乎起了作用。。。我甚至没有发现语法错误。很抱歉给您带来麻烦-以下是工作代码:
<xsl:template match="*">
<xsl:call-template name="sumItems">
<xsl:with-param name="nodeSet" select="//item/id[text()=(//itemList/id)]/.." />
</xsl:call-template>
</xsl:template>
<xsl:template name="sumItems">
<xsl:param name="nodeSet" />
<xsl:param name="tempSum" select="0" />
<xsl:choose>
<xsl:when test="not($nodeSet)">
<xsl:value-of select="$tempSum" />
</xsl:when>
<xsl:otherwise>
<xsl:variable name="value" select="$nodeSet[1]/value" />
<xsl:call-template name="sumItems">
<xsl:with-param name="nodeSet" select="$nodeSet[position() > 1]" />
<xsl:with-param name="tempSum" select="$tempSum + $value" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
使用用声明的键,然后可以使用键'item-by-id',//itemList/id来选择itemList/id元素引用的item元素,并使用sumkey'item-by-id',//itemList/id/value来计算值元素的和。这似乎也起到了作用,因此我将其标记为答案,因为它最终比我丑陋的select语句读起来更好
select="//item/id[text()=(//itemList/id)]/.."
<xsl:template match="*">
<xsl:call-template name="sumItems">
<xsl:with-param name="nodeSet" select="//item/id[text()=(//itemList/id)]/.." />
</xsl:call-template>
</xsl:template>
<xsl:template name="sumItems">
<xsl:param name="nodeSet" />
<xsl:param name="tempSum" select="0" />
<xsl:choose>
<xsl:when test="not($nodeSet)">
<xsl:value-of select="$tempSum" />
</xsl:when>
<xsl:otherwise>
<xsl:variable name="value" select="$nodeSet[1]/value" />
<xsl:call-template name="sumItems">
<xsl:with-param name="nodeSet" select="$nodeSet[position() > 1]" />
<xsl:with-param name="tempSum" select="$tempSum + $value" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>