获取当前节点的值

Ale*_*ski 7 xml xslt xpath

我对术语并不是很熟悉,所以我甚至不确定问题的标题是否准确,但我会尽力解释.

我有以下XML示例.

<countries>
  <country name="Afghanistan" population="22664136" area="647500">
    <language percentage="11">Turkic</language>
    <language percentage="35">Pashtu</language>
    <language percentage="50">Afghan Persian</language>
  </country>
</countries>
Run Code Online (Sandbox Code Playgroud)

我将XPath用于语言节点(/ countries/country /,然后是for-each for languages).

<language percentage="11">Turkic</language>
Run Code Online (Sandbox Code Playgroud)

使用XSLT如何在上面的例子"Turkic"中输出值.我想不出另一种表达问题的方法,但它就像我在节点,并且不知道获取此节点的值的语法.

提前致谢

joe*_*rgl 11

xsl:value-of元素和current()功能应该做的伎俩:

<xsl:value-of select="current()"/>
Run Code Online (Sandbox Code Playgroud)

我不知道模板的确切结构,但是例如下面的一个输出语言名称:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/countries">
    <xsl:for-each select="country">
      <xsl:value-of select="current()"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

  • 注意:使用`//`不是一个好主意,这意味着"在任何深度都有该名称的节点"(后代或自我).使用`match ="/ countries"`和`select ="country"`代替,它只选择孩子,而不是任何深度的后代.使用`//`通常被认为是"邪恶的",因为它可以引入许多微妙的错误(来自重叠的节点)并且具有性能损失(它必须再次遍历每个节点,而不仅仅是一个子集). (3认同)
  • 或者简单地说:`<xsl:value-of select ="."/>` (2认同)
  • @ michael.hor257k:让我们补充一下,`.`与`current()`不同。在`select =“ foo [。='test']”`与`select =“ foo [current()='test']”`中,点将其焦点更改为每个`foo`元素,即,它更改_inside_ XPath表达式,而current()则将焦点集中在当前XPath的当前上下文项_outside_上(即,当前xsl:template或xsl:for-each的上下文项)。微小的,通常是微妙的但重要的差异。 (2认同)
  • @Abel不带。我只想再次强调一下,为了OP的好处:`&lt;xsl:value-of select =“ current()” /&gt;`和`&lt;xsl:value-of select =“。” /&gt;`完全相同东西-在规范中说得很对:http://www.w3.org/TR/xslt/#misc-func-还应注意,严格来讲,`不是`current()的快捷方式`; “ current()”函数是一个“ XSLT”函数,而“。”是上下文节点的一个“ XPath”缩写,即“ self :: node()”。碰巧的是,当在最外面的表达式中使用“ current()”时,“ *当前节点总是与上下文节点相同*”(同上)。 (2认同)