XPath按部门(几个部门)查找最大总和

时间:2015-09-25 08:59:14

标签: xml xpath sum

如何找到最昂贵的部门?

我需要使用XPath 1.0找到最昂贵的部门(deptno)。接下来是我的XML文档的结构。

    <employee deptno="10" empno="7369" mgr="7902">
        <ename>SMITH</ename>
        <sal>800.00</sal>
    </employee>
    <employee deptno="30" empno="7499" mgr="7698">
        <ename>ALLEN</ename>
        <sal>1600.00</sal>
    </employee>
    <employee deptno="30" empno="7521" mgr="7698">
        <ename>WARD</ename>
        <sal>1250.00</sal>
    </employee>
    <employee deptno="20" empno="7566" mgr="7839">
        <ename>JONES</ename>
        <sal>2975.00</sal>
    </employee>
    <employee deptno="30" empno="7654" mgr="7698">
        <ename>MARTIN</ename>
        <sal>1250.00</sal>
    </employee>
    <employee deptno="30" empno="7698" mgr="7839">
        <ename>BLAKE</ename>
        <sal>2850.00</sal>
    </employee>
    <employee deptno="10" empno="7782" mgr="7839">
        <ename>CLARK</ename>
        <sal>2450.00</sal>
    </employee>
    <employee deptno="20" empno="7788" mgr="7566">
        <ename>SCOTT</ename>
        <sal>3000.00</sal>
    </employee>
    <employee deptno="10" empno="7839">
        <ename>KING</ename>
        <sal>5000.00</sal>
    </employee>
    <employee deptno="30" empno="7844" mgr="7698">
        <ename>TURNER</ename>
        <sal>1500.00</sal>
    </employee>
    <employee deptno="20" empno="7876" mgr="7788">
        <ename>ADAMS</ename>
        <sal>1100.00</sal>
    </employee>
    <employee deptno="30" empno="7900" mgr="7698">
        <ename>JAMES</ename>
        <sal>950.00</sal>
    </employee>
    <employee deptno="20" empno="7902" mgr="7566">
        <ename>FORD</ename>
        <sal>3000.00</sal>
        <comm>0.0</comm>
    </employee>
    <employee deptno="10" empno="7934" mgr="7782">
        <ename>MILLER</ename>
        <sal>1300.00</sal>
    </employee>

结果必须是编号为20的部门,因为总和20 dept = 10075&gt; 9550(dept 10)> 9400(dept 30)。

编辑:添加了新版XML文档

2 个答案:

答案 0 :(得分:0)

也许是这样的:

/employee/sal[not(. < ../../sal)][1]

可在此thread

上找到更多示例

答案 1 :(得分:0)

我认为你不能xpath - 我可能会突然出现perl

#!/usr/bin/env perl
use strict;
use warnings;
use XML::Twig;

my %sum_of_depts;

my $twig = XML::Twig->parsefile('my_file.xml');
foreach my $employee ( $twig->findnodes('//employee') ) {
    my $deptid = $employee->att('deptno');
    my $sal    = $employee->first_child_text('sal');
    $sum_of_depts{$deptid} += $sal;
}

foreach my $deptid ( sort { $sum_of_depts{$b} <=> $sum_of_depts{$a} }
    keys %sum_of_depts )
{
    print "$deptid => $sum_of_depts{$deptid}\n";
}

给出您的样本输入给出了:

20 => 10075
10 => 9550
30 => 9400