考虑这个简单的 xml 元素示例:
<parent foo="1" bar="2" foobar="3">
<child/>
</parent>
在 xsl 文件中,我处于“父”的上下文中(即在 中)。我想根据字符串变量选择一个节点集(在示例中,只有一个属性)。例如,我想选择一个与 $attribute-name 匹配的节点集。我将展示我失败的 xsl 示例,您可能会明白我要做什么。
<xsl:template match="parent">
<xsl:call-template name="print-value-of">
<xsl:with-param name="attribute-type" select="'foo'"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="print-value-of">
<xsl:param name="attribute-type"/>
<xsl:value-of select="$attribute-type"/>
</xsl:template>
这将打印输出:
foo
我最初打算做的(但我意识到这不是它应该做的)是:
IE。我想让它打印的是:
1
问题 :我怎样才能实现这种行为?
通知 : 我知道我在 这个简单的案例 , 可以将实际属性节点作为参数传递(即
我真正想做的是创建一个通用的函数模板,它可以:
<编辑>
我只能使用 XSLT 1.0,所以 1.0 解决方案更受欢迎!
编辑>
<编辑2>
关于类似主题的后续问题:是否还可以使用字符串变量指定的名称/类型创建 a 的属性? IE。
<xsl:attribute name="$attribute-type"/>
像上面的行那样做会导致 $attribute-type 成为 xml 输出中属性的字面名称。相反,我希望它再次评估变量并将评估值作为名称。
最佳答案
这将选择一个名为 'foo'
的属性。 .
<xsl:call-template name="print-value-of">
<xsl:with-param name="attribute-type" select="@*[name() = 'foo']"/>
</xsl:call-template>
<xsl:template name="print-value-of">
<xsl:param name="attribute-type"/>
<xsl:value-of select="."/>
</xsl:template>
或者,您可以留下
<xsl:call-template>
就像这样,并在您的模板中进行更改:<xsl:template name="print-value-of">
<xsl:param name="attribute-type"/>
<xsl:value-of select="@*[name() = $attribute-type]"/>
</xsl:template>
无论如何,除非这只是一个综合示例,否则以上所有内容都是一种非常昂贵的说法:
<xsl:value-of select="@*[name() = $attribute-type]"/>
编辑:
要使用动态名称创建属性,请使用:
<xsl:attribute name="{$attribute-type}">
<xsl:value-of select="$some-value-or-expression" />
</xsl:attribute>
请注意,大括号使 XSLT 处理器评估它们的内容(仅在属性值中)。
您应该确保
$attribute-type
包含符合 XML 命名规则的字符串。您应该考虑将变量重命名为 $attribute-name
,因为就是这样。
关于xml - 选择与字符串变量名称匹配的节点集(属性或元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1300195/