开发者

xpath find value of current node

I have several nodes with same Name='UPC' and I need to find the value of the current one.

开发者_运维问答<XML>
<Attribute>
      <Name>UPC</Name>
      <Type>ComplexAttr</Type>
      <Value>Testing</Value>
    </Attribute>
    <Attribute>
      <Name>UPC</Name>
      <Type>ComplexAttr</Type>
      <Value>24a</Value>
    </Attribute>
</XML>

Expected Output: It should pull the value from /Attribute/Value where Name='UPC' and Type = 'ComplexAttr'.

On the first run = 'Testing' & On the 2nd run the value should be = '24a'

I'm trying to use the following code but it is not working. The value is null.

<xsl:attribute name ="value">
    <xsl:value-of select =".//Attribute[Type='ComplexAttr' and Name = 'UPC'][$i]/Value" />
</xsl:attribute>

where $i is the variable I'm using to loop through the above xml and it increments after each run. However, it only gives me the same value 'Testing' (which is the first value) in every run. I have checked the value of the variable. It is changing every time it loops through.

I have also tried using current() and position() like below but I'm getting null in this case.

<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" />

Can someone help me out with this. Thanks in Advance.


This is one of the biggest FAQ:

The [] operator binds stronger than the // abbreviation.

In order to select the 1st element in the XML document, that satisfies the specific condition in the predicate, use:

(//Attribute[Type='ComplexAttr' and Name = 'UPC'])[1]/Value

In order to select the 2nd element in the XML document, that satisfies the specific condition in the predicate, use:

(//Attribute[Type='ComplexAttr' and Name = 'UPC'])[2]/Value

In order to select the $ith element in the XML document, that satisfies the specific condition in the predicate, use:

(//Attribute[Type='ComplexAttr' and Name = 'UPC'])[position() = $i]/Value


You can't use a variable in an XPath expression. Try manually using a constant and you'll see that it works:

<xsl:value-of select=".//Attribute[Type='ComplexAttr' and Name='UPC'][2]/Value" />

In general, you don't really write loops in XSLT, even though the syntax allows it. You write templates that are invoked with a particular context at a particular point in time. I'm not sure what the best next step is without knowing more about the context of the overall program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜