In this document we will show you how to create a Xml
structure which contains the "books" objects defined in the previous
documentation. Remember that in the previous example we had a
Xml structure and by using parse method of Xml.pm module we
created a Xml object. Now we do not have a structure, we want to
create one. For this case a Xml object is created by using the
new method of Xml.pm class.
This method takes one argument that is the name of the fist element
of the Xml structure we want to create. For example for books
structure this will be "books".
Once we created this object, we can call
its methods to set the values of given elements and their attributes.
The following program shows how it is being done.
The names of these methods are the name of the elements. These
methods take one or two arguments. The first argument is the value
of the element we want to set. The second argument is a hash
reference and is used to set the values of attributes. The keys of
this hash reference are the names of the attributes we want to set.
use Xml;
my $books = Xml->new(books);
my $book1 = Xml->new(book);
$book1->title("Perl Cookbook");
$book1->isbn("1-56592-243-3");
$book1->author("Tom Cristiansen", { age => 30, height => "175cm" });
$book1->author("Nathan Torkington", { age => 31, height => "183cm" });
my $book2 = Xml->new(book);
$book2->title("Advenced Perl Programming");
$book2->isbn("1-56592-220-4");
$book2->author("Sriram Srinivasan", { age => 32, height => "170cm" });
my $book3 = Xml->new(book);
$book3->title("Mastering Algorithms with Perl");
$book3->isbn("1-56592-398-7");
$book3->author("Jon Orwant", { age => 33, height => "unknown" });
$book3->author("Jarko Hietaniemi", { age => 34, height => "unknown" });
$book3->author("John Macdonald", { age => 35, height => "unknown" });
$books->book($book1);
$books->book($book2);
$books->book($book3);
# to get output from your program
# replace bottom line with
# print $books->string;
# or
# $books->print;
$books->string;
|
|