View RSS Feed

Java XML

Creating DOM Child Elements

Rate this Entry
by , 04-27-2012 at 06:10 PM (2349 Views)
This lesson shows you how to create root and child elements in the DOM tree. We will first create a blank DOM document and add the root element to it. Then I show you how to add comment element and then child element to the root element. In this example following xml code will generated and displayed on the console.
XML Code:
<?xml version="1.0" encoding="UTF-8" ?> 
<root>
<!-- This is comment--> 
<Child attribute1="The value of Attribute 1" /> 
</root>
Creating the root element
In the previous lesson you learned how to create DocumentBuilder object and the create a blank DOM document. The following code creates a blank document.
Java Code:
//Create blank DOM Document
Document doc = docBuilder.newDocument();
The createElement function is used to create the root element and appendChild method is used to append the element to the DOM document.
Java Code:
//create the root element
Element root = doc.createElement("root");
//all it to the xml tree
doc.appendChild(root);
Adding Comment Element to DOM Tree
The doc.createComment function is used to create Comment object.
Java Code:
//create a comment
Comment comment = doc.createComment("This is comment");
//add in the root element
root.appendChild(comment);
Adding Child Element to DOM Tree
The doc.createElement function is used to create Child element.
Java Code:
//create child element
Element childElement = doc.createElement("Child");
//Add the atribute to the child
childElement.setAttribute("attribute1","The value of Attribute 1");
root.appendChild(childElement);

Submit "Creating DOM Child Elements" to Facebook Submit "Creating DOM Child Elements" to Digg Submit "Creating DOM Child Elements" to del.icio.us Submit "Creating DOM Child Elements" to StumbleUpon Submit "Creating DOM Child Elements" to Google

Categories
DOM

Comments