Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have this xml assigned to a variable called "$data":
<employees> <employee> <empid>9</empid> <fname>Joe</fname> <lname>A</lname> </employee> <employee> <empid>3</empid> <fname>Larry</fname> <lname>W</lname> </employee> <employee> <empid>7</empid> <fname>Perl</fname> <lname>L</lname> </employee> </employees>
I have this perl script which uses XML::Simple to parse the xml file:
$parsed = eval {XMLin($data)}; if ($@) { print $@; } else { <NEED SORTING CODE HERE> }
So, what i need is to be able to sort the XML using the <empid> tag...so the xml should be sorted like this:
<employees> <employee> <empid>3</empid> <fname>Larry</fname> <lname>W</lname> </employee> <employee> <empid>7</empid> <fname>Perl</fname> <lname>6</lname> </employee> <employee> <empid>9</empid> <fname>Joe</fname> <lname>A</lname> </employee> </employees>

Replies are listed 'Best First'.
Re: sorting on subkey of hash of hashes
by Tanktalus (Canon) on Sep 16, 2005 at 03:47 UTC

    Just the other day, I posted some code that sorted stuff in HTML using XML::Twig - I think that the same idea could be employed here.

Re: sorting on subkey of hash of hashes
by goldclaw (Scribe) on Sep 16, 2005 at 10:15 UTC
    I dont know exactly the return of XLMin, but Im guessing you want soemthing like this:
    my @sorted = sort { $a->{empid} <=> $b->{empid} } @{$parsed->{employees}};
    gc
Re: sorting on subkey of hash of hashes
by radiantmatrix (Parson) on Sep 16, 2005 at 16:33 UTC

    Your variable $parsed should now contain a hash ref which looks like:

    { 'employee' => [ { 'empid' => '9', 'lname' => 'A', 'fname' => 'Joe' }, { 'empid' => '3', 'lname' => 'W', 'fname' => 'Larry' }, { 'empid' => '7', 'lname' => '6', 'fname' => 'Perl' } ] };

    So, you want to sort the array referenced by the value of the 'employee' key:

    @{ $parsed->{'employee'} } = sort { $a->{'empid'} <=> $b->{'empid'} } @{ $parsed->{'employee'} }; print XMLout($parsed, NoAttr=>1, RootName=>'employees');

    This will print:

    <employees> <employee> <empid>3</empid> <fname>Larry</fname> <lname>W</lname> </employee> <employee> <empid>7</empid> <fname>Perl</fname> <lname>6</lname> </employee> <employee> <empid>9</empid> <fname>Joe</fname> <lname>A</lname> </employee> </employees>
    <-radiant.matrix->
    Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
    The Code that can be seen is not the true Code
    "In any sufficiently large group of people, most are idiots" - Kaa's Law