For example, we're going to write a program that
manages a simple, prioritized
"to-do" list that uses an XML
datafile to store entries. Each item in the list has an
"immediate" or
"long-term" priority. The program
will initialize the list if it's empty or the file
is missing. The user can add items by using -i or
-l (for
"immediate" or
"long-term," respectively),
followed by a description. Finally, the program updates the datafile
and prints it out on the screen.
Example 6-7. To-do list manager, first part
use XML::TreeBuilder;
use XML::Element;
use Getopt::Std;
# command line options
# -i immediate
# -l long-term
#
my %opts;
getopts( 'il', \%opts );
# initialize tree
my $data = 'data.xml';
my $tree;
# if file exists, parse it and build the tree
if( -r $data ) {
$tree = XML::TreeBuilder->new( );
$tree->parse_file($data);
# otherwise, create a new tree from scratch
} else {
print "Creating new data file.\n";
my @now = localtime;
my $date = $now[4] . '/' . $now[3];
$tree = XML::Element->new( 'todo-list', 'date' => $date );
$tree->push_content( XML::Element->new( 'immediate' ));
$tree->push_content( XML::Element->new( 'long-term' ));
}
A few notes on initializing the structure are necessary. The minimal
structure of the datafile is this:
<todo-list date="DATE">
<immediate></immediate>
<long-term></long-term>
</todo-list>
As long as the <immediate> and
<long-term> elements are present, we have
somewhere to put schedule items. Thus, we need to create three
elements using the XML::Element constructor method
new( ), which uses its argument to set the name of
the element. The first call of this method also includes an argument
'date' => $date to create an attribute named
"date." After creating element
nodes, we have to connect them. The push_content(
) method adds a node to an element's
content list.