View Full Version : Resolved DomDocument->change parent of a node.

08-22-2009, 12:50 PM
Hi all,
I've an xml file with the following DTD

<!ELEMENT discussionGroups ( group+ ) >
<!ATTLIST discussionGroups xml:id NMTOKEN #REQUIRED >

<!ELEMENT group ( group* ) >
<!ATTLIST group xml:id ID #REQUIRED >

I need to move a group-node from the current position and attach as a child of another element. I'm just learning xml, so I couldn't make the expected output.
Here is my current code,
public function transferGroup($newGroupId){
$dom = new DomDocument('1.0', 'UTF-8');
$dom->validateOnParse = true;
$childnodes = $node->getElementsByTagName('group');
// making sure that the $newGroupId is not a child group
foreach($childnodes as $child){
$xmlId= explode('_', $child->getAttribute('xml:id'));
return false; //not possible to move
$newnode = $dom->createElement('group');
# Creating a new node by getting current values
$value1 = $dom->createTextNode($node->getAttribute('xml:id'));

$value2 = $dom->createTextNode($node->getAttribute('name'));

return true;
My intention is to change the parent of node having an id = $this->GroupId to the node having id=$newGroupId

My current logic is

Get all the chidnodes of 'this' node and make sure that the parent is not going to be a child of 'this'
Create a new node by getting the attributes of 'this' node and after that delete 'this' node from DOM
Append the newly created node as the child of node having id=$newGroupId

I think it's working now after some struggle, but Is there a way to simplify the entire function?
Got it. It's as simple as
$newnode = $node->parentNode->removeChild($node);
$dom->getElementById('id_'.$newGroupId)->appendChild($newnode); :o

Any help would be apreciated.