xpath查找当前节点的值

问题描述

| 我有几个具有相同Name = \'UPC \'的节点,我需要找到当前节点的值。
<XML>
<Attribute>
      <Name>UPC</Name>
      <Type>ComplexAttr</Type>
      <Value>Testing</Value>
    </Attribute>
    <Attribute>
      <Name>UPC</Name>
      <Type>ComplexAttr</Type>
      <Value>24a</Value>
    </Attribute>
</XML>
预期产量: 它应该从/ Attribute / Value中提取值,其中Name = \'UPC \'和Type = \'ComplexAttr \'。 第一次运行= \'Testing \'& 在第二次运行中,该值应为= \'24a \' 我正在尝试使用以下代码,但无法正常工作。该值为空。
<xsl:attribute name =\"value\">
    <xsl:value-of select =\".//Attribute[Type=\'ComplexAttr\' and Name = \'UPC\'][$i]/Value\" />
</xsl:attribute>
其中$ i是我用来遍历上述xml的变量,并且每次运行后都会递增。但是,它在每次运行中只给我相同的值\'Testing \'(这是第一个值)。我已经检查了变量的值。每次循环时它都在变化。 我也尝试过使用current()和position(),如下所示,但在这种情况下,我会得到null。
<xsl:value-of select =\".//Attribute[Type=\'ComplexAttr\' and Name = \'UPC\'][current()]/Value\" />

<xsl:value-of select =\".//Attribute[Type=\'ComplexAttr\' and Name = \'UPC\'][position() = $i]/Value\" />
有人可以帮我这个忙。提前致谢。     

解决方法

这是最大的常见问题之一:
[]
运算符的绑定强度大于
//
的缩写。 为了在XML文档中选择满足谓词中特定条件的第一个元素,请使用:
(//Attribute[Type=\'ComplexAttr\' and Name = \'UPC\'])[1]/Value
为了在XML文档中选择满足谓词中特定条件的第二个元素,请使用:
(//Attribute[Type=\'ComplexAttr\' and Name = \'UPC\'])[2]/Value
为了选择满足谓词中特定条件的XML文档中的第7个元素,请使用:
(//Attribute[Type=\'ComplexAttr\' and Name = \'UPC\'])[position() = $i]/Value
    ,您不能在XPath表达式中使用变量。尝试使用常量手动操作,您会看到它起作用:
<xsl:value-of select=\".//Attribute[Type=\'ComplexAttr\' and Name=\'UPC\'][2]/Value\" />
通常,即使语法允许,您也不会真正在XSLT中编写循环。您编写在特定时间点使用特定上下文调用的模板。我不确定下一步最好的方法是不了解整个程序的上下文。