Building XML Trees With PHP - Killing Off The Kids
(Page 6 of 11 )
You've already seen that you can also add elements to an existing tree via the addChild() method. But XMLTree also allows you to prune an existing document tree, deleting elements from the hierarchy with the removeChild() method.
In order to illustrate this, consider the following example, which dynamically constructs a simple document tree:
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree();
// add the root element
$root =& $tree->addRoot("superhero");
//
add child elements
$name =& $root->addChild("name", "Peter Parker aka Spiderman");
$age =&
$root->addChild("age", 21); $sex =& $root->addChild("sex", "male");
$location
=& $root->addChild("location", "Manhattan");
// print tree
$tree->dump();
?>
Here's the output:
<?xml version="1.0"?>
<superhero>
<name>Peter Parker aka Spiderman</name>
<age>21</age>
<sex>male</sex>
<location>Manhattan</location>
</superhero>
Now's let's suppose I wanted to remove the <age> element from the tree. With
removeChild(), it's a piece of cake:
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree();
// add the root element
$root =& $tree->addRoot("superhero");
//
add child elements
$name =& $root->addChild("name", "Peter Parker aka Spiderman");
$age =&
$root->addChild("age", 21); $sex =& $root->addChild("sex", "male");
$location
=& $root->addChild("location", "Manhattan");
// remove second child node
(age)
$root->removeChild(1);
// print tree
$tree->dump();
?>
The removeChild() method takes, as argument, the index number of the child to
be removed under the specified Node object (remember that node numbering begins at 0, not 1). In this case, since I want to remove the <age> element, which is the second child of the root element, I can use
<?php
$root->removeChild(1);
?>
to get the job done.
And here's the revised output:
<?xml version="1.0"?>
<superhero>
<name>Peter Parker aka Spiderman</name>
<sex>male</sex>
<location>Manhattan</location>
</superhero>
Next: Rank And File >>
More PHP Articles
More By icarus, (c) Melonfire