tags:

views:

45

answers:

1

This is part of the XML I want to edit

<ScrapBook>
  <Event>
   <Name> Name of Event <Name>
   <Other Elements>
  </Event>
<ScrapBook>

I need to modify the Name of the Event.

I am able to delete the node using remove_child. But I dont know how to add another element at the same spot.

This is my code:

   public function editEventName($oldEventName, $newEventName){
        $xmlDoc = new DOMDocument();
        $xmlDoc->load($this->xmlFileName);
        $events = $xmlDoc->getElementsByTagName("Event");
        foreach($events as $event){
            $eventNames = $event->getElementsByTagName("Name");
            $eventN = $eventNames->item(0)->nodeValue;
            if($oldEventName == $eventN){
                $nud = $eventNames->item(0)->parentNode;
                $nud->removeChild($eventNames->item(0));

                // set name to $newEventName
            }
            $xmlDoc->saveXML();
 $xmlDoc->save($this->xmlFileName);
        }
A: 

A solution, if I understand the question correctly, might be to just overwrite the value of $eventNames->item(0)->nodeValue, without trying to remove the node and add a new one.

For instance, using your code, and modifying a little so it works for that simpler case :

$str = <<<XML
<ScrapBook>
  <Event>
   <Name> Name of Event </Name>
   <Blah>glop glop</Blah>
  </Event>
</ScrapBook>
XML;

$xmlDoc = new DOMDocument();
$xmlDoc->loadXml($str);
$events = $xmlDoc->getElementsByTagName("Event");
foreach($events as $event){
    $eventNames = $event->getElementsByTagName("Name");
    $eventN = $eventNames->item(0)->nodeValue;
    if(' Name of Event ' == $eventN){
        $eventNames->item(0)->nodeValue = 'New name';
    }
}
var_dump($xmlDoc->saveXML());

Will get me :

string '<?xml version="1.0"?>
<ScrapBook>
  <Event>
   <Name>New name</Name>
   <Blah>glop glop</Blah>
  </Event>
</ScrapBook>
' (length=119)

And the value of the Name of the Event has been replaced by "New name".

Pascal MARTIN
Thank You so much !! I dint know this was possible
Milee
You're welcome :-) Have fun !
Pascal MARTIN