Using Perl With XML (part 2) - Welcome To The Human Race
(Page 5 of 9 )
Just as it's possible to access elements and their content, it's also possible to access element attributes and their values. The getAttributes() method of the Node object provides access to a list of all available attributes, and the getNamedItem() and getValue() methods make it possible to access specific attributes and their values. Take a look at a demonstration of how it all works:
#!/usr/bin/perl
# create an XML-compliant string
$xml = "<?xml version=\"1.0\"?><me species=\"human\"><name>Joe
Cool</name><age>24</age><sex>male</sex></me>";
# include package
use XML::DOM;
# instantiate parser
$xp = new XML::DOM::Parser();
# parse and create tree
$doc = $xp->parse($xml);
# get root node (Node object)
$root = $doc->getDocumentElement();
# get attributes (NamedNodeMap object)
$attribs = $root->getAttributes();
# get specific attribute (Attr object)
$species = $attribs->getNamedItem("species");
# get value of attribute
# returns "human"
print $species->getValue();
# end
Getting to an attribute value is a little more complicated than getting to an element. But hey - no gain without pain, right?
Next: Building A Library >>
More Perl Articles
More By icarus, (c) Melonfire