appending a new node

K

Kleist

Hello,

I use DOM XML PHP functions to build a document. Is it
possible to insert a new node as sibling right after the
selected by xpath node? There is a function insert_before()
but it seems that it appends a child?

TIA,

K.
 
M

Martin Honnen

Kleist wrote:

I use DOM XML PHP functions to build a document. Is it possible to
insert a new node as sibling right after the selected by xpath node?
There is a function insert_before() but it seems that it appends a child?

In PHP 5 it should work alike
node->parentNode->insertBefore(newNode, node->nextSibling);

as in the following complete example

<?php
$xmlDocument = new DOMDocument('1.0', 'UTF-8');
$loaded = $xmlDocument->loadXML('
<gods>
<god name="Kibo" />
<god name="Xibo" />
</gods>');

$newGod = $xmlDocument->createElement('god');
$newGod->setAttribute('name', 'Maho');

$xpathEvaluator = new DOMXPath($xmlDocument);
$oldGod = $xpathEvaluator->query('/gods/god[@name = "Kibo"]',
$xmlDocument)->item(0);
if ($oldGod != NULL) {
$oldGod->parentNode->insertBefore($newGod, $oldGod->nextSibling);
}

header('Content-Type: application/xml');
echo $xmlDocument->saveXML();
?>
 
J

Janwillem Borleffs

Kleist said:
Unfortunally I have only PHP 4.3.1 on my server, and this
will not do. But anyway thanks for replay

The following looks a bit cumbersome but appears to do the trick:

<?php

if (!$dom = domxml_open_mem('<doc><child id="0" /><child id="2" /></doc>'))
{
echo "Error while parsing the document\n";
exit;
}

$xpath = xpath_new_context($dom);
$root = $dom->document_element();

$element = $dom->create_element('child');
$element->set_attribute('id', 1);

$nodeset = xpath_eval($xpath, '//child[@id=0]');
$node = $nodeset->nodeset[0];

if ($sibling = $node->next_sibling()) {
$root->insert_before($element, $sibling);
} else {
$node->append_sibling($element);
}

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";

?>


JW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top