Adding a Node to a DOM Document

This example demonstrates how to insert a node into a DOM relative to another node. In particular, a text node is inserted around an element node.
// Create a new DOM document; this method is implemented in // Creating an Empty DOM Document Document doc = createDomDocument(); // Insert the root element node Element element = doc.createElement("root"); doc.appendChild(element); // Insert a comment in front of the element node Comment comment = doc.createComment("a comment"); doc.insertBefore(comment, element); // Add a text node to the element element.appendChild(doc.createTextNode("D")); // Add a text node to the beginning of the element element.insertBefore(doc.createTextNode("A"), element.getFirstChild()); // Add a text node before the last child of the element element.insertBefore(doc.createTextNode("C"), element.getLastChild()); // Add another element after the first child of the root element Element element2 = doc.createElement("item"); element.insertBefore(element2, element.getFirstChild().getNextSibling()); // Add a text node in front of the new item element element2.getParentNode().insertBefore(doc.createTextNode("B"), element2);
This is the resulting XML:
<?xml version="1.0" encoding="UTF-8"?> <!--a comment--><root>AB<item/>CD</root>

Comments

15 Feb 2010 - 1:23am by Anonymous (not verified)

Thanks for putting comments each of your codes. For me it's easy to follow and understand.

18 Feb 2010 - 7:41am by Anonymous (not verified)

That's how I started with the DOMDocument trying to render pages. But I decided to create a PHP DOM Template Engine that takes all the repetitiveness away. I posted it at torrent SE it is now an opensource project.

It does a great job of simplifying DOM and separating design from development. It also handles forms so you can render select elements fast and easy. Check it out!

2 Mar 2010 - 6:26am by Anonymous (not verified)

Agreed with first commentator. I mean some places even go to the length of starting with 5 empty spaces + code just to make it understandable for anyone wanting to see how the code works. Commenting is very very appreciated.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.