Sample Application Using XML::Twig

The Perl script:

#!/bin/perl -w

#########################################################################
# #
# This simple example shows how to create a twig, parse a file, get #
# the root of the document, its children, access a specific child and #
# get the text of an element #
# #
#########################################################################

use strict;
use XML::Twig;

my $field= $ARGV[0] || 'lastname';
my $twig= new XML::Twig;

$twig->parsefile( "sample.xml");
my $root= $twig->root;
my @entries= $root->children;

my @sorted = sort { $a->first_child( $field)->text cmp $b->first_child( $field)->text } @entries;

foreach my $entry (@sorted)
{
my $firstname = $entry->first_child()->text;
my $lastname = $entry->first_child()->next_sibling->text;
my $company = $entry->first_child('company')->text;

print "$firstname $lastname from $company\n\n";
}

Back
Next