Xpath find the value of the current node

I have several nodes with the 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 Result: It should pull the value from / Attribute / Value, where Name = 'UPC' and Type = 'ComplexAttr'.

In the first run = 'Testing' & In the second step, the value should be = '24a'

I am trying to use the following code, but it does not work. 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 that I use to iterate over the above xml and it increases after each run. However, it only gives me one “ Test ” value (which is the first value) in each run. I checked the value of the variable. He changes every time he passes.

I also tried using current () and position () as shown below, but in this case I get 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" /> 

Can someone help me with this. Thanks at Advance.

+4
source share
2 answers

This is one of the biggest FAQs :

The operator [] bound more strongly than the abbreviation // .

To select the 1st element in an XML document that satisfies a specific condition in the predicate, use :

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

To select the second element in an XML document that satisfies a specific condition in the predicate, use :

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

To select the $i th element in an XML document that satisfies a certain condition in the predicate, use :

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

You cannot use a variable in an XPath expression. Try it manually using a constant and you will see that it works:

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

In general, you don't actually write loops in XSLT, although the syntax allows this. You write patterns that are invoked with a specific context at a specific point in time. I'm not sure what the best next step is, not knowing more about the context of the overall program.

+2
source

Source: https://habr.com/ru/post/1347817/


All Articles