将XSLT的部分限制为单个节点

时间:2012-03-29 16:05:18

标签: xslt

是否有办法将XSLT的一部分限制为单个节点,以便每次都不需要整个节点路径?

例如......

Name: <xsl:value-of select="/root/item[@attrib=1]/name"/>
Age: <xsl:value-of select="/root/item[@attrib=1]/age"/>

这可以通过for-each命令完成,但我认为如果可能的话应该避免这些......

<xsl:for-each select="/root/item[@attrib=1]"/>
  Name: <xsl:value-of select="name"/>
  Age: <xsl:value-of select="age"/>
</xsl:for-each>

我想我在问是否有一个与VB.NET With命令相同的XSLT?

为了便于阅读,我宁愿避免使用xsl:template,因为有问题的XSLT文件很大,但很高兴接受,如果这是唯一的方法。如果是这样,基于特定节点调用特定模板的语法是什么?

更新

在跟进@javram的答案后,可以根据特定的属性/节点匹配不同的模板。

<xsl:apply-templates select="/root/item[@attrib=1]"/>
<xsl:apply-templates select="/root/item[@attrib=2]"/>

<xsl:template match="/root/item[@attrib=1]">
  Name: <xsl:value-of select="name"/>
  Age: <xsl:value-of select="age"/>
</xsl:template>

<xsl:template match="/root/item[@attrib=2]">
  Foo: <xsl:value-of select="foo"/>
</xsl:template>

4 个答案:

答案 0 :(得分:2)

您可以使用变量:

<xsl:variable name="foo" select="/root/item[@attrib=1]" />

<xsl:value-of select="$foo/name" />
<xsl:value-of select="$foo/age" />

答案 1 :(得分:2)

正确的方法是使用模板:

<xsl:apply-templates select="/root/item[@attrib=1]"/>

.
.
.

<xsl:template match="/root/item">
     Name: <xsl:value-of select="name"/>
     Age: <xsl:value-of select="age"/>
</xsl:template>

答案 2 :(得分:0)

在XSLT 2.0中,另一种可能的风格是:

<xsl:value-of select='/root/item[@attrib=1]/
                       concat("Name: ", name, " Age: ", age)'/>

答案 3 :(得分:0)

此:

<xsl:for-each select="/root/item[@attrib=1]"/>
  Name: <xsl:value-of select="name"/>
  Age: <xsl:value-of select="age"/>
</xsl:for-each>

逐个下降到所有节点(每个匹配节点)。

此:

<xsl:for-each select="(/root/item[@attrib=1])[1]"/>
  Name: <xsl:value-of select="name"/>
  Age: <xsl:value-of select="age"/>
</xsl:for-each>

下降到第一个(可能只有)匹配节点,并且等同于你希望的VB.NET With语句。