Log in

View Full Version : add a new node to an existing xml



yingzhao
04-09-2006, 07:51 PM
Hi,

I need to add a new xml node to a exisiting xml. The xml is like this,



$xmlTmpl = '<template><item><id>0</id><name>pipe</name><description>blah, blah...</description><unit>m</unit></item><item><id>1</id><name>concrete</name><description>blah...</description><unit>t</unit></item></template>';
I am using DOMElement to create a new xml element and the appendChild method to add this new node to the end of the xml
as below.



$doc = new DOMDocument();
$doc->loadXML($xmlTmpl);
$tmpl = $doc->documentElement;
$items = $tmpl->getElementsByTagName('item');

//create a new element
$itemid = $items->length;
$newItem = $doc->createElement('item');
$idNode = $doc->createElement('id',$itemid);
$nameNode = $doc->createElement('name', $name);
$dscpNode = $doc->createElement('description', $dscp);
$unitNode = $doc->createElement('unit', $unit);
$newItem->appendChild($idNode);
$newItem->appendChild($nameNode);
$newItem->appendChild($dscpNode);
$newItem->appendChild($unitNode);

//add the new element as a child of the xml root
$tmpl -> appendChild($newItem);

$xmlTmpl = $doc->saveXML();

This snippet throws an error on me at line, $tmpl -> appendChild($newItem);. The error is,

Only one top level element is allowed in an XML document. Error processing resource 'http://localhost/contest/getTemplate.php'. Line 6, Position 2

Can anyone shed some lights? Many thanks.

dragon
05-24-2006, 08:02 PM
not sure . . . I am not to good with xml