XSLT如何获得匹配的第一个节点

时间:2014-09-22 21:13:56

标签: xml xslt

我有一个像这样的XML:

<a>
  <b attribute="yes" />
  <c attribute="yes" />
  <c attribute="yes" />
</a>

如何获得此匹配的第一个节点:

a/c[@attribute = 'yes']/../b[@attribute='yes' or @attribute='no']

我尝试在表达式的末尾添加[1],但它确实不起作用,因为当有多个<c attribute="yes" />时,我会得到几个<b>

3 个答案:

答案 0 :(得分:1)

你可以像这样重写你的表达......

a[c[@attribute = 'yes']]/b[@attribute='yes' or @attribute='no']

这意味着您可以获得第一个这样的

a[c[@attribute = 'yes']]/b[@attribute='yes' or @attribute='no'][1]

当然,这假设没有多个a元素(即a实际上不是根元素)。在这种情况下,你可以写这个......

(a[c[@attribute = 'yes']]/b[@attribute='yes' or @attribute='no'])[1]

答案 1 :(得分:1)

  

我尝试在表达式的末尾添加[1],但事实并非如此   工作

我不确定您想要什么,但在表达式 的末尾添加[1]似乎有效。如果我们将输入更改为:

<a>
  <b attribute="yes"  />
  <c attribute="yes" id="1"/>
  <c attribute="yes" id="2"/>
</a>

然后:

<xsl:template match="/">
    <xsl:copy-of select="a/c[@attribute = 'yes']/../c[@attribute='yes' or @attribute='no'][1]"/>
</xsl:template>

返回:

<c attribute="yes" id="1"/>

也许你应该编辑你的问题并用简单的非技术语言解释你在这里尝试实现的目标。


修改

响应您的编辑:它应该仍然有用。使用以下输入:

<a>
  <b attribute="yes" id="1" />
  <c attribute="yes" id="2"/>
  <c attribute="yes" id="3"/>
  <b attribute="yes" id="4" />
</a>

这条指令:

<xsl:copy-of select="a/c[@attribute = 'yes']/../b[@attribute='yes' or @attribute='no'][1]"/>

返回:

<b attribute="yes" id="1"/>

答案 2 :(得分:1)

而不是a/b/c[1],您需要(a/b/c)[1]。否则,[1]仅适用于路径中的最后一步,它会选择每个c的第一个a/b

相关问题