In the previous documentation the xml elements did not have
any attributes. In this document we demonstrate a simple xml
document which contains some element with attributes.
In the following example we added author element to the book element.
We also included two attributes called age and height in the author
element. Given book may have one or more authors. Note that
title and isbn elements do not
have any attributes. If an element does not have any atribute, the
method carresponding to element tag name returns a string which
contains the value of the element. However if an element has any
attribute, than return value of same method is array of
Leaf objects. The value method
of this object returns the value of the element. The attribute
values are returned by methods of Leaf object
carresponding to attribute names. For example name
attribute's value returned by name method.
Similarly age
attribute's value returned by age method.
Following example demonstrates this.
<books>
<book>
<title>Perl Cookbook</title>
<isbn>1-56592-243-3</isbn>
<author height = 175cm
age = 30>
Tom Cristiansen </author>
<author age = 31 height = 183cm>Nathan Torkington</author>
</book>
<book>
<title>Advenced Perl Programming</title>
<isbn>1-56592-220-4</isbn>
<author age = "32" height = '170cm' >Sriram Srinivasan</author>
</book>
<book>
<title>Mastering Algorithms with Perl</title>
<isbn>1-56592-398-7</isbn>
<author height = unknown age = 33>Jon Orwant</author>
<author age = 34 height = 180cm>Jarko Hietaniemi</author>
<author age = 35 height = unknown>John Macdonald</author>
</book>
</books> |
use Xml;
my $books = Xml->parse($xml);
my @book = $books->book;
foreach $bk ( @book ) {
print $bk->title,"\n";
print $bk->isbn,"\n";
my @author = $bk->author;
foreach $auth ( @author ) {
print "NAME = ",$auth->value,"\n";
print "AGE = ",$auth->age,"\n";
print "HEIGHT = ",$auth->height,"\n";
}
print "----------------------------\n";
}
|
| Perl Cookbook 1-56592-243-3 NAME = Tom Cristiansen AGE = 30 HEIGHT = 175cm NAME = Nathan Torkington AGE = 31 HEIGHT = 183cm ---------------------------- Advenced Perl Programming 1-56592-220-4 NAME = Sriram Srinivasan AGE = 32 HEIGHT = 170cm ---------------------------- Mastering Algorithms with Perl 1-56592-398-7 NAME = Jon Orwant AGE = 33 HEIGHT = unknown NAME = Jarko Hietaniemi AGE = 34 HEIGHT = 180cm NAME = John Macdonald AGE = 35 HEIGHT = unknown ---------------------------- |