|
JAXP API using DOM Parser |
|
used to append the element to the DOM
document.
//create the root element
Element root = doc.createElement(“root”);
//all it to the xml tree
doc.appendChild(root); |
(2) Adding Comment Element to DOM Tree
The doc.createComment method is used to
reate Comment object.
//create a comment
Comment comment =
doc.createComment(“This is comment”);
//add in the root element
root.appendChild(comment); |
(3) Adding Child Element to DOM Tree
The doc.createElement method is used to
create Child element.
//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); |
(4) Printing the DOM Tree on console
An finally we will print the DOM tree on the
console with the following code:
TransformerFactory tranFactory =
TransformerFactory.newInstance();
Transformer aTransformer =
tranFactory.newTransformer();
Source src = new DOMSource(doc);
Result dest = new
StreamResult(System.out);
aTransformer.transform(src, dest); |
|
|
|
Here is the full source code of CreateDomXml.java
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import
javax.xml.transform.stream.StreamResult;
class CreateDomXml
{
public static void main(String[] args)
{
try{
//Create instance of
DocumentBuilderFactory
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//Get the DocumentBuilder
DocumentBuilder docBuilder =
factory.newDocumentBuilder();
//Create blank DOM Document
Document doc =
docBuilder.newDocument();
//create the root element
Element root =
doc.createElement(“root”);
//add it to the xml tree
doc.appendChild(root);
//create a comment
Comment comment =
doc.createComment(“This is comment”);
//add in the root element
root.appendChild(comment);
//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);
TransformerFactory tranFactory =
TransformerFactory.newInstance();
Transformer aTransformer =
tranFactory.newTransformer();
Source src = new DOMSource(doc);
Result dest = new
StreamResult(System.out);
|
|
|
Mar
2008 | Java Jazz Up | 20 |
|
|
|
View All Topics |
All Pages of this Issue |
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
Download PDF |
|
|
|
|
|
|
|
|
|