This section provides a tutorial example on how to write a program to create a new DOM document object with DOM classes and methods like: DocumentBuilder.newDocument(), Document.createElement(), Document.createTextNode(), and Node.appendChild().
DOM documents can also be created from scratch instead of parsed from an XML file.
This can be easily done by using the following methods:
DocumentBuilder.newDocument(): Create an empty DOM document.
Document.createElement(): Create a new Element.
Document.createTextNode(): Create a new TextNode.
Node.appendChild(): Insert a sub Node into the current Node.
Element.setAttribute(): Add new attribute into an element.
The following program shows how to create a simple DOM document with these methods:
/**
* DOMNewDoc.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
class DOMNewDoc {
public static void main(String[] args) {
try {
DocumentBuilderFactory f
= DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document d = b.newDocument();
Element r = d.createElement("dictionary");
d.appendChild(r);
Element w = d.createElement("word");
r.appendChild(w);
Element e = d.createElement("update");
w.appendChild(e);
e.setAttribute("date","2002-12-24");
e = d.createElement("name");
w.appendChild(e);
e.setAttribute("is_acronym","true");
e.appendChild(d.createTextNode("DTD"));
e = d.createElement("definition");
w.appendChild(e);
e.appendChild(d.createTextNode("Document Type Definition"));
printNode(d, "");
} catch (ParserConfigurationException e) {
System.out.println(e.toString());
}
}
static void printNode(Node n, String p) {
NodeList l = n.getChildNodes();
NamedNodeMap m = n.getAttributes();
int ml = -1;
if (m!=null) ml = m.getLength();
System.out.println(p+n.getNodeName()+": "+n.getNodeType()+", "
+l.getLength()+", "+ml+", "+n.getNodeValue());
for (int i=0; i<ml; i++) {
Node c = m.item(i);
printNode(c,p+" |-");
}
for (int i=0; i<l.getLength(); i++) {
Node c = l.item(i);
printNode(c,p+" ");
}
}
}