They say there's more than one way to skin a cat - and that'stwice as true when you're a Perl developer. In this concluding article onXML parsing with Perl, find out how the XML::DOM package provides analternative technique for manipulating XML elements and attributes, andcompare the two approaches to see which one works best for you.
Once you've obtained a reference to a node, a number of other methods become available to help you obtain the name and value of that node, as well as references to parent and child nodes. Take a look:
# create an XML-compliant string
$xml = "<?xml version=\"1.0\"?><me><name>Joe
# include package
# instantiate parser
$xp = new XML::DOM::Parser();
# parse and create tree
$doc = $xp->parse($xml);
# get root node
$root = $doc->getDocumentElement();
# get name of root node
# returns "me"
# get children as array
@children = $root->getChildNodes();
# this is the "name" element under "me"
# I could also have used $root->getFirstChild() to get here
$firstChild = $children;
# returns "name"
# returns "1"
# now to access the value of the text node under "name"
$text = $firstChild->getFirstChild();
# returns "Joe Cool"
# returns "#text"
# returns "3"
# go back up the tree
# start from the "name" element and get its parent
$parent = $firstChild->getParentNode();
# check the name - it should be "me"
# yes it is!
As you can see, the getNodeName() and getNodeType() methods provide access to basic information about the node currently under examination. The children of this node can be obtained with the getChildNodes() method previously discussed, and node parents can be obtained with the getParentNode() method. It's fairly simple, and - once you play with it a little - you'll get the hang of how it works.
A quick note on the getNodeType() method above: every node is of a specific type, and this property returns a numeric code corresponding to the type. A complete list of defined types is available in the Perl documentation for the XML::DOM package.
Note also that the text within an element's opening and closing tags is treated as a child node of the corresponding element node, and is returned as an object. This object comes with a getData() method, which returns the actual content nested within the element's opening and closing tags. You'll see this again in a few pages.