in reply to XML::Twig -- sorting by attribute
OK, here is my take (using the latest CPAN version of XML::Twig). The only difficult thing here is how to match elements which do _not_ have the vob attribute. I have to look at the XPath spec (Matt?) to figure out how to express it... and then add it to the module. In the meantime I use a coderef to get it (to compute @vob_not I use an anonymous sub that returns true if the element does not have a vob attribute).
#!/bin/perl -w use strict; use XML::Twig; my $twig= new XML::Twig; $twig->parse( \*DATA); # build the twig my $root= $twig->root; # get the root of the twig (stats) my @vob_not = $root->children( sub { my $elt= shift; !$elt->att( 'v +ob')}); my @vob_none = $root->children( q{player[@vob="none"]} ); my @vob_letter = $root->children( q{player[@vob=~/^[a-z]$/]}); @vob_letter = sort { $a->att( 'vob') cmp $b->att( 'vob') } @vob_letter; my %letters= map { $_->att( 'vob') => 1 } @vob_letter; print "No attribute or vob=none\n", "-" x 20, "\n"; foreach my $player (@vob_not) { printf( "%-20s\n", $player->field( 'name')); } foreach my $player (@vob_none) { printf( "%-20s....none\n", $player->field( 'name')); } print "\n", join( ', ', sort keys %letters), "\n", "-" x 20, "\n"; foreach my $player (@vob_letter) { printf( "%-20s....%1s\n", $player->field( 'name'), $player->att( ' +vob')); } __DATA__ <stats><player vob="d" ><name>Houston, Allan</name><g>69</g></player> <player vob="z" ><name>Sprewell, Latrell</name><g>69</g></player> <player vob="a" ><name>Ewing, Patrick</name><g>49</g></player> <player vob="none" ><name >Johnson, Larry</name><g>57</g></player> <player vob="g" ><name>Camby, Marcus</name><g>48</g></player> <player vob="d" ><name>Thomas, Kurt</name><g>67</g><ppg>7.9</ppg></pla +yer> <player vob="none" ><name >Ward, Charlie</name><g>59</g><ppg>7.5</ppg> +</player> <player vob="none" ><name>Wallace, John</name><g>55</g><ppg>6.6</ppg>< +/player> <player><name>Childs, Chris</name><g>61</g><ppg>5.3</ppg></player> <player><name>Duncan, Tim</name><g>66</g><ppg>23.1</ppg></player> <player><name>Robinson, David</name><g>68</g><ppg>17.1</ppg></player> </stats>
Update: note that this is not really the most efficient way, XML::Twig will go through the entire list of children for each list it builds), just the easiest to write.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: XML::Twig -- sorting by attribute
by Novitiatus (Novice) on Jan 31, 2002 at 19:36 UTC | |
by mirod (Canon) on Jan 31, 2002 at 19:43 UTC | |
|
Re: Re: XML::Twig -- sorting by attribute
by Novitiatus (Novice) on Feb 01, 2002 at 22:43 UTC |