📄 5_create.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><!--NewPage--><html><head><title>Create & Manipulate a DOM</title><style type="text/css"><!----></style></head><body BGCOLOR="#ffffff"><table width="100%"> <tr> <td align=left> <ahref="4_tree.html"><img src="../images/PreviousArrow.gif" width=26 height=26 align=bottom border=0 alt="Previous | "></a><a href="6_ns.html"><img src="../images/NextArrow.gif" width=26 height=26 align=bottom border=0 alt="Next | "></a><a href="../alphaIndex.html"><img src="../images/xml_IDX.gif" width=26 height=26 align=bottom border=0 alt="Index | "></a><a href="../TOC.html"><imgsrc="../images/xml_TOC.gif" width=26 height=26 align=bottom border=0 alt="TOC | "></a><a href="../index.html"><imgsrc="../images/xml_Top.gif" width=26 height=26 align=bottom border=0 alt="Top | "></a> </td> <td align=right><strong><em><a href="index.html">Top</a></em></strong> <a href="../TOC.html#intro"><strong><em>Contents</em></strong></a> <a href="../alphaIndex.html"><strong><em>Index</em></strong></a> <a href="../glossary.html"><strong><em>Glossary</em></strong></a> </td> </tr></table><p> <center> <IMG SRC="../images/shoeline2.gif" ALIGN="BOTTOM" BORDER="0" WIDTH="202" HEIGHT="25" NATURALSIZEFLAG="3"> <IMG SRC="../images/shoeline2.gif" ALIGN="BOTTOM" BORDER="0" WIDTH="202" HEIGHT="25" NATURALSIZEFLAG="3"> </center><blockquote> <blockquote> <hr size=4> </blockquote></blockquote><p> <h2> 5. Creating and Manipulating a DOM</h2><table width="40%" border="1" align="right"> <tr> <td> <div align="center"><b><i>Link Summary</i></b></div> </td> </tr> <tr> <td> <dl> <dt><b><i>Exercise Links</i></b></dt> </dl> <ul> <li><a href="work/DomEcho05.java"><code>DomEcho05.java</code></a></li> <li><a href="work/DomEcho06.java"><code>DomEcho06.java</code></a></li> </ul> <dl> <dt><b><i>API Links</i></b></dt> </dl> <ul> <li><a href="../../api/org/w3c/dom/Node.html">org.w3c.dom.Node</a></li> <li><a href="../../api/org/w3c/dom/Element.html">org.w3c.dom.Element</a></li> </ul> <dl> <dt><b><i>Glossary Terms</i></b></dt> </dl> <dl> <dd> <a href="../glossary.html#normalization">normalization</a><br> </dd> </dl> </td> </tr></table><p> 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.<h3><a name="factory"></a>Obtaining a DOM from the Factory</h3><p>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.<blockquote> <p> </blockquote><p><b>Note:</b> <br> The code discussed in this section is in <a href="work/DomEcho05.java"><code>DomEcho05.java</code></a>.</p><h4><a name="code"></a>Modify the Code</h4><p>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:</p><blockquote> <pre>public class DomEcho05 extends JPanel{ ... <old><strike>boolean compress = true;</strike></old> <new><b>boolean compress = false;</b></new></pre></blockquote><p>Next, you need to create a <tt>buildDom</tt> method that creates the <tt>document</tt> object. The easiest way to do that is to create the method and then copy the DOM-construction section from the <tt>main</tt> method to create the <code>buildDom</code>. The modifications shown below show you the changes you need to make to make that code suitable for the <tt>buildDom</tt> method. <blockquote> <pre>public class DomEcho05 extends JPanel{ ... public static void makeFrame() { ... } <new><b>public static void buildDom ()</b></new> <new><b>{</b></new> <new><b>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();</b></new> <new><b>try {</b></new> <new><b>DocumentBuilder builder = factory.newDocumentBuilder();</b></new> <old><strike>document = builder.parse( new File(argv[0]) );</strike></old> document = builder.newDocument(); // Create from whole cloth <old><strike>} catch (SAXParseException spe) {</strike></old> <old><strike>...</strike></old> <old><strike>} catch (SAXException sxe) {</strike></old> <old><strike>...</strike></old><old><strike></strike></old> } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); <old><strike>} catch (IOException ioe) {</strike></old> <old><strike>...</strike></old><old><strike></strike></old> } }</pre></blockquote><blockquote><p> </blockquote><p>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: SAXParseException, SAXException, and IOException. </p><p>Finally, since you are going to be working with Element objects, add the statement to import that class at the top of the program:</p><blockquote> <pre>import org.w3c.dom.Document;import org.w3c.dom.DOMException;<new><b>import org.w3c.dom.Element;</b></new></pre></blockquote><h4><a name="nodes"></a>Create Element and Text Nodes</h4><p>Now, for your first experiment, add the Document operations to create a root node and several children:</p><blockquote> <p></p> <pre>public class DomEcho05 extends JPanel{ ... <new>public static void buildDom ()</new> <new>{</new> <new>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();</new> <new>try {</new> <new>DocumentBuilder builder = factory.newDocumentBuilder();</new> document = builder.newDocument(); // Create from whole cloth <b>Element root = (Element) document.createElement("rootElement"); document.appendChild (root); root.appendChild( document.createTextNode("Some") ); root.appendChild( document.createTextNode(" ") ); root.appendChild( document.createTextNode("text") );</b> } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } }</pre> </blockquote><p>Finally, modify the argument-list checking code at the top of the <tt>main</tt> method so you invoke <tt>buildDom</tt> and <tt>makeFrame</tt> instead of generating an error, as shown below:</p><blockquote> <p></p> <pre>public class DomEcho05 extends JPanel{ ... public static void main (String argv []) { if (argv.length != 1) { <old><strike>System.err.println ("Usage: java DomEcho filename");</strike></old> <old><strike>System.exit (1);</strike></old> <new><b>buildDom();</b></new> <new><b>makeFrame();</b></new> <new><b>return;</b></new> } </pre> <p> </blockquote><p>That's all there is to it! Now, if you supply an argument the specified file to be parsed and, if you don't, the experimental code that builds a DOM is executed. </p><h4><a name="run"></a>Run the App</h4><p>Compile and run the program with no arguments produces the result shown in Figure 1: </p><blockquote> <img src="images/p500a.gif" width="640" height="440"><br> <i><b>Figure 1: Element Node and Text Nodes Created</b></i> </blockquote><blockquote> <p> </blockquote><h3><a name="normalize"></a>Normalizing the DOM</h3><p>In this experiment, you'll manipulate the DOM you created by normalizing it (cf. <a href="../glossary.html#normalization">normalization</a>) after it has been constructed.</p><blockquote> <p><b>Note:</b> <br> The code discussed in this section is in <a href="work/DomEcho06.java"><code>DomEcho06.java</code></a>.</p> <p> </blockquote><p>Add the code highlighted below to normalize the DOM:. </p><blockquote> <p></p> <pre> public static void buildDom () { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { ... root.appendChild( document.createTextNode("Some") ); root.appendChild( document.createTextNode(" ") ); root.appendChild( document.createTextNode("text") ); <new></new><new></new><new><b>document.getDocumentElement().normalize();</b></new> } catch (ParserConfigurationException pce) { ...</pre></blockquote><p>In this code, <new><tt>getDocumentElement</tt> returns the document's root node</new>, and the <tt>normalize</tt> operation manipulates the tree under it. </p>When you compile and run the app now, the result looks like Figure 2: <blockquote> <p><img src="images/p600b.gif" width="640" height="440"><br> <i><b>Figure 2: Text Nodes Merged After Normalization</b></i></p></blockquote><p>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.</p><blockquote> <p><b>Note:</b><br> Now that you have this program to experiment with, see what happens to other combinations of CDATA, entity references, and text nodes when you normalize the tree.</p></blockquote><h3><a name="other"></a>Other Operations</h3><p>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:\</p><ul> <li>Traversing nodes</li> <li>Creating attributes</li> <li>Removing nodes</li></ul><h4><a name="traverse"></a>Traversing Nodes</h4><p>The <a href="../../api/org/w3c/dom/Node.html">org.w3c.dom.Node</a> interface defines a number of methods you can use to traverse nodes, including <tt>getFirstChild</tt>, <tt>getLastChild</tt>, <tt>getNextSibling</tt>, <tt>getPreviousSibling</tt>, and <tt>getParentNode</tt>. Those operations are sufficient to get from anywhere in the tree to any other location in the tree. </p><h4><a name="create"></a>Creating Attributes</h4><p>The <a href="../../api/org/w3c/dom/Element.html">org.w3c.dom.Element</a> interface, which extends Node, defines a <tt>setAttribute</tt> operation, which adds an attribute to that node. (A better name from the Java platform standpoint would have been <tt>addAttribute</tt>, since the attribute is not a property of the class, and since a new object is created.) </p><p>You can also use the Document's <tt>createAttribute</tt> operation to create an instance of Attribute, and use an overloaded version of <code>setAttribute</code> to add that.</p><h4><a name="remove"></a>Removing and Changing Nodes</h4><p>To remove a node, you use its parent <a href="../../api/org/w3c/dom/Node.html">Node</a>'s <code>removeChild</code> method. To change it, you can either use the parent node's <code>replaceChild</code> operation or the node's <tt>setNodeValue</tt> operation. </p><h4></h4><h3><a name="finish"></a>Finishing Up</h3>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! <blockquote> <p> <hr size=4></blockquote><p> <p> <table width="100%"> <tr> <td align=left> <a href="4_tree.html"><img src="../images/PreviousArrow.gif" width=26 height=26 align=top border=0 alt="Previous | "></a><ahref="6_ns.html"><img src="../images/NextArrow.gif" width=26 height=26 align=top border=0 alt="Next | "></a><a href="../alphaIndex.html"><img src="../images/xml_IDX.gif" width=26 height=26 align=top border=0 alt="Index | "></a><a href="../TOC.html"><imgsrc="../images/xml_TOC.gif" width=26 height=26 align=top border=0 alt="TOC | "></a><a href="../index.html"><imgsrc="../images/xml_Top.gif" width=26 height=26 align=top border=0 alt="Top | "></a> </td> <td align=right><strong><em><a href="index.html">Top</a></em></strong> <a href="../TOC.html#intro"><strong><em>Contents</em></strong></a> <a href="../TOC.html#intro"><strong><em></em></strong></a> <a href="../alphaIndex.html"><strong><em>Index</em></strong></a> <a href="../glossary.html"><strong><em>Glossary</em></strong></a></td> </tr></table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -