Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Sort n Create XML

by misc (Pilgrim)
on Aug 20, 2007 at 09:41 UTC ( #633755=note: print w/ replies, xml ) Need Help??


in reply to Sort n Create XML

TIMTOWTDI :-)
Here is my version, utilizing XML::Twig

#!/usr/bin/perl -w use strict; use warnings; use XML::Twig; my $t= XML::Twig->new(pretty_print=>'indented'); $t->parse( join('',<DATA>) ); $t->root->sort_children( sub{ my $e = shift; return 0 if $e->tag eq 'header'; return 10000000 if $e->tag eq 'footer'; my @strength = $e->getElementsByTagName('strength') or + die "Malformed element:\n".$e->sprint; return $strength[0]->text; }, type=>'numeric' ); $t->print; __DATA__ <?xml version="1.0" encoding="UTF-8"?> <system> <header></header> <class> <name>Eight</name> <strength>8</strength> </class> <class> <name>Four</name> <strength>4</strength> </class> <class> <name>Ten</name> <strength>10</strength> </class> <class> <name>One</name> <strength>1</strength> </class> <footer></footer> </system>
The sort sub function is quite ugly and buggy,
if you are going to use Twig, you should either print the header, footer and the sorted classes in separate prints or surround all classes with a e.g. <allclasses> tag.

I just wanted to give an idea how you could use Twig for the job.


Comment on Re: Sort n Create XML
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://633755]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2014-09-30 23:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (385 votes), past polls