beginner
beginner

Reputation: 431

XPath expression to compute arithmetics on array of nodes

<record>
    <node_1>
        <value_1_0>5</value_1_0>
        <value_1_1>0</value_1_1>
        <value_1_2>10</value_1_2>
        <value_1_3>8</value_1_3>
    </node_1>
   .................................
   .................................

    <node_63>
        <value_63_0>1</value_63_0>
        <value_63_1>99</value_63_1>
        <value_63_2>53</value_63_2>
        <value_63_3>5</value_63_3>
  </node_63>
</record>

Problem statement : How to write efficient XPath expressions for these two cases?

if value is non zero for any node, I need to check if value of that particular subnode for previous and next node are non zero. i.e. if node_50/value_50_0 is non zero, node49/value_49_0 and node51/value_51_0 should also be non zero. Similarly, for rest of the cases.

Next, it should add up the values for alternate nodes. i.e. node_1/value_1_0 + node_3/value_1_0 + ... + node_63/value_1_0. Similarly, for value_1_1,...,value_63_1 and so on.

I am wondering if there is any "for loop" with counter variable provision for each index, so that the XPath expression will be simple for both cases?

pseudo code :

for(i=1; i<64; i++)
   for(j=0;j<4;j++)
     if (node_i/value_i_j !=0)&& (node_i-1/value_i-1_j !=00)&&(node_i-1/value_i-1_j!=0)
       True
     else
       False
   end
 end

Upvotes: 0

Views: 50

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

Using

let $alternate-nodes := /record/*[position() mod 2 = 1]
for $i in (1 to count($alternate-nodes[1]/*))
return 
  sum($alternate-nodes/*[position() eq $i])

should do to compute the sums. Of course the use of for $i in is only necessary if the element names are really as complicated as in the input where each has one or two index numbers in the name.

For the test for zero or non-zero values should be possible with e.g.

let $nodes := /record/*
for $i in (1 to count($nodes[1]/*))
return every $value in $nodes/*[position() eq $i] satisfies $value != 0

to return a sequence of boolean values.

Upvotes: 1

Related Questions