Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sum function in XPath?

Tags:

xml

xpath

I have an xml file with following contents:

<Xavor>
<Dev>
    <Emp>1</Emp>
    <Floor>1</Floor>
    <Salary>1200.4</Salary>
</Dev>
<Dev>
    <Emp>2</Emp>
    <Salary>3100.8</Salary>
</Dev>
<Dev>
    <Emp>3</Emp>
    <Floor>1</Floor>
</Dev>

I want to calculate sum of salaries of first two Employees using sum function. I came to this XPath:

sum(/Xavor/Dev[2]/Salary/text())

But this returns only second salary value ie 3100.8!!! This XPath was working fine when there were only non-floating point numbers were in salaries. Please help me out.

like image 589
Azeem Avatar asked Nov 02 '11 11:11

Azeem


2 Answers

Try this:

sum(/Xavor/Dev[position() &lt;= 2]/Salary/text())
like image 194
Rubens Farias Avatar answered Oct 20 '22 01:10

Rubens Farias


In addition to the correct answer by @Rubens Farias, if you want to sum the salaries of all Dev that have (numeric) salaries specified, use:

sum(/*/Dev/Salary[number(.) = number(.)])
like image 39
Dimitre Novatchev Avatar answered Oct 20 '22 01:10

Dimitre Novatchev