Home TOC |
![]() ![]() ![]() |
Creating and Manipulating a DOM
By now, you understand the structure of the nodes that make up a DOM. A DOM is actually very easy to create. This section of the DOM tutorial is going to take much less work than anything you've see up to now. All the foregoing work, however, generated the basic understanding that will make this section a piece of cake.
Obtaining a DOM from the Factory
In this version of the application, you're still going to create a document builder factory, but this time you're going to tell it create a new DOM instead of parsing an existing XML document. You'll keep all the existing functionality intact, however, and add the new functionality in such a way that you can "flick a switch" to get back the parsing behavior.
Note: The code discussed in this section is inDomEcho05.java
.
Modify the Code
Start by turning off the compression feature. As you work with the DOM in this section, you're going to want to see all the nodes:
public class DomEcho05 extends JPanel { ... boolean compress = true; boolean compress = false;Next, you need to create a
buildDom
method that creates thedocument
object. The easiest way to do that is to create the method and then copy the DOM-construction section from themain
method to create thebuildDom
. The modifications shown below show you the changes you need to make to make that code suitable for thebuildDom
method.public class DomEcho05 extends JPanel { ... public static void makeFrame() { ... } public static void buildDom() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse( new File(argv[0]) ); document = builder.newDocument(); // Create from whole cloth } catch (SAXException sxe) { ... } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } catch (IOException ioe) { ... } }In this code, you replaced the line that does the parsing with one that creates a DOM. Then, since the code is no longer parsing an existing file, you removed exceptions which are no longer thrown:
SAXException
andIOException
.And since you are going to be working with
Element
objects, add the statement to import that class at the top of the program:import org.w3c.dom.Document; import org.w3c.dom.DOMException; import org.w3c.dom.Element;Create Element and Text Nodes
Now, for your first experiment, add the
Document
operations to create a root node and several children:public class DomEcho05 extends JPanel { ... public static void buildDom() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); // Create from whole cloth Element root = (Element) document.createElement("rootElement"); document.appendChild(root); root.appendChild( document.createTextNode("Some") ); root.appendChild( document.createTextNode(" ") ); root.appendChild( document.createTextNode("text") ); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } }Finally, modify the argument-list checking code at the top of the
main
method so you invokebuildDom
andmakeFrame
instead of generating an error, as shown below:public class DomEcho05 extends JPanel { ... public static void main(String argv[]) { if (argv.length != 1) { System.err.println("Usage: java DomEcho filename"); System.exit(1); buildDom(); makeFrame(); return; }That's all there is to it! Now, if you supply an argument the specified file is parsed and, if you don't, the experimental code that builds a DOM is executed.
Run the App
Compile and run the program with no arguments produces the result shown in Figure 12:
Figure 12 Element Node and Text Nodes Created
Normalizing the DOM
In this experiment, you'll manipulate the DOM you created by normalizing it after it has been constructed.
Note: The code discussed in this section is inDomEcho06.java
.
Add the code highlighted below to normalize the DOM:.
public static void buildDom() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { ... root.appendChild( document.createTextNode("Some") ); root.appendChild( document.createTextNode(" ") ); root.appendChild( document.createTextNode("text") ); document.getDocumentElement().normalize(); } catch (ParserConfigurationException pce) { ...In this code,
getDocumentElement
returns the document's root node, and thenormalize
operation manipulates the tree under it.When you compile and run the app now, the result looks like Figure 13:
Figure 13 Text Nodes Merged After Normalization
Here, you can see that the adjacent text nodes have been combined into a single node. The normalize operation is one that you will typically want to use after making modifications to a DOM, to ensure that the resulting DOM is as compact as possible.
Note: Now that you have this program to experiment with, see what happens to other combinations ofCDATA
, entity references, and text nodes when you normalize the tree.
Other Operations
To complete this section, we'll take a quick look at some of the other operations you might want to apply to a DOM, including:
Traversing Nodes
The
org.w3c.dom.Node
interface defines a number of methods you can use to traverse nodes, includinggetFirstChild
,getLastChild
,getNextSibling
,getPreviousSibling
, andgetParentNode
. Those operations are sufficient to get from anywhere in the tree to any other location in the tree.Creating Attributes
The
org.w3c.dom.Element
interface, which extends Node, defines asetAttribute
operation, which adds an attribute to that node. (A better name from the Java platform standpoint would have beenaddAttribute
, since the attribute is not a property of the class, and since a new object is created.)You can also use the
Document
'screateAttribute
operation to create an instance ofAttribute
, and use an overloaded version ofsetAttribute
to add that.Removing and Changing Nodes
To remove a node, you use its parent
Node
'sremoveChild
method. To change it, you can either use the parent node'sreplaceChild
operation or the node'ssetNodeValue
operation.Finishing Up
Congratulations! You've learned how a DOM is structured and how to manipulate it. And you now have a DomEcho application that you can use to display a DOM's structure, condense it down to GUI-compatible dimensions, and experiment with to see how various operations affect the structure. Have fun with it!
Home TOC |
![]() ![]() ![]() |