📄 jaxpdom7.html
字号:
<a name="wp65042"> </a><p class="pBody">In this code, <code class="cCode">getDocumentElement</code> returns the document's root node, and the <code class="cCode">normalize</code> operation manipulates the tree under it. </p><a name="wp65046"> </a><p class="pBody">When you compile and run the application now, the result looks like <a href="JAXPDOM7.html#wp65052">Figure 6-14</a>: </p><a name="wp65050"> </a><p class="pBody"></p><div align="left"><img src="images/pd-600b13.gif" height="241" width="376" alt="Text Nodes Merged After Normalization" border="0" hspace="0" vspace="0"/></div><p class="pBody"></p><p> <a name="65052"> </a><strong><font >Figure 6-14 Text Nodes Merged After Normalization</font></strong></p><a name="wp65053"> </a><p class="pBody">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><hr><a name="wp65054"> </a><p class="pNote">Note: Now that you have this program to experiment with, see what happens to other combinations of <code class="cCode">CDATA</code>, entity references, and text nodes when you normalize the tree.</p><hr><a name="wp65056"> </a><h3 class="pHeading2">Other Operations</h3><a name="wp65057"> </a><p class="pBody">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><div class="pSmartList1"><ul class="pSmartList1"><a name="wp65058"> </a><div class="pSmartList1"><li>Traversing nodes</li></div><a name="wp75111"> </a><div class="pSmartList1"><li>Searching for nodes</li></div><a name="wp75123"> </a><div class="pSmartList1"><li>Obtaining node content</li></div><a name="wp65059"> </a><div class="pSmartList1"><li>Creating attributes</li></div><a name="wp65060"> </a><div class="pSmartList1"><li>Removing and changing nodes</li></div><a name="wp75108"> </a><div class="pSmartList1"><li>Inserting nodes</li></div></ul></div><a name="wp65062"> </a><h4 class="pHeading3">Traversing Nodes</h4><a name="wp65063"> </a><p class="pBody">The <code class="cCode">org.w3c.dom.Node</code> interface defines a number of methods you can use to traverse nodes, including <code class="cCode">getFirstChild</code>, <code class="cCode">getLastChild</code>, <code class="cCode">getNextSibling</code>, <code class="cCode">getPreviousSibling</code>, and <code class="cCode">getParentNode</code>. Those operations are sufficient to get from anywhere in the tree to any other location in the tree. </p><a name="wp75112"> </a><h4 class="pHeading3">Searching for Nodes</h4><a name="wp75099"> </a><p class="pBody">However, when you are searching for a node with a particular name, there is a bit more to take into account. Although it is tempting to get the first child and inspect it to see if it is the right one, the search has to account for the fact that the first child in the sublist could be a comment or a processing instruction. If the XML data wasn't validated, it could even be a text node containing ignorable whitespace.</p><a name="wp75338"> </a><p class="pBody">In essence, you need to look through the list of child nodes, ignoring the ones that are of no concern, and examining the ones you care about. Here is an example of the kind of routine you need to write when searching for nodes in a DOM hierarchy. It is presented here in its entirety (complete with comments) so you can use it for a template in your applications.</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">/** * Find the named subnode in a node's sublist. * <li>Ignores comments and processing instructions. * <li>Ignores TEXT nodes (likely to exist and contain ignorable whitespace, * if not validating. * <li>Ignores CDATA nodes and EntityRef nodes. * <li>Examines element nodes to find one with the specified name. * </ul> * @param name the tag name for the element to find * @param node the element node to start searching from * @return the Node found */public Node findSubNode(String name, Node node) { if (node.getNodeType() != Node.ELEMENT_NODE) { System.err.println("Error: Search node not of element type"); System.exit(22); } if (! node.hasChildNodes()) return null; NodeList list = node.getChildNodes(); for (int i=0; i < list.getLength(); i++) { Node subnode = list.item(i); if (subnode.getNodeType() == Node.ELEMENT_NODE) { if (subnode.getNodeName() == name) return subnode; } } return null;}<a name="wp75339"> </a></pre></div><a name="wp75673"> </a><p class="pBody">For a deeper explanation of this code, see <a href="JAXPDOM2.html#wp68475">Increasing the Complexity</a> in <a href="JAXPDOM2.html#wp67733">When to Use DOM</a>.</p><a name="wp77628"> </a><p class="pBody">Note, too, that you can use APIs described in <a href="JAXPDOM5.html#wp75940">Summary of Lexical Controls</a> to modify the kind of DOM the parser constructs. The nice thing about this code, though, is that will work for most any DOM.</p><a name="wp75118"> </a><h4 class="pHeading3">Obtaining Node Content</h4><a name="wp75119"> </a><p class="pBody">When you want to get the text that a node contains, you once again need to look through the list of child nodes, ignoring entries that are of no concern, and accumulating the text you find in <code class="cCode">TEXT</code> nodes, <code class="cCode">CDATA</code> nodes, and <code class="cCode">EntityRef</code> nodes.</p><a name="wp75161"> </a><p class="pBody">Here is an example of the kind of routine you need to use for that process:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">/** * Return the text that a node contains. This routine:<ul> * <li>Ignores comments and processing instructions. * <li>Concatenates TEXT nodes, CDATA nodes, and the results of * recursively processing EntityRef nodes. * <li>Ignores any element nodes in the sublist. * (Other possible options are to recurse into element sublists * or throw an exception.) * </ul> * @param node a DOM node * @return a String representing its contents */public String getText(Node node) { StringBuffer result = new StringBuffer(); if (! node.hasChildNodes()) return ""; NodeList list = node.getChildNodes(); for (int i=0; i < list.getLength(); i++) { Node subnode = list.item(i); if (subnode.getNodeType() == Node.TEXT_NODE) { result.append(subnode.getNodeValue()); } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) { result.append(subnode.getNodeValue()); } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) { // Recurse into the subtree for text // (and ignore comments) result.append(getText(subnode)); } } return result.toString();}<a name="wp75653"> </a></pre></div><a name="wp75658"> </a><p class="pBody">For a deeper explanation of this code, see <a href="JAXPDOM2.html#wp68475">Increasing the Complexity</a> in <a href="JAXPDOM2.html#wp67733">When to Use DOM</a>.</p><a name="wp77640"> </a><p class="pBody">Again, you can simplify this code by using the APIs described in <a href="JAXPDOM5.html#wp75940">Summary of Lexical Controls</a> to modify the kind of DOM the parser constructs. But the nice thing about this code, once again, is that will work for most any DOM.</p><a name="wp75655"> </a><h4 class="pHeading3">Creating Attributes</h4><a name="wp65066"> </a><p class="pBody">The <code class="cCode">org.w3c.dom.Element</code> interface, which extends Node, defines a <code class="cCode">setAttribute</code> operation, which adds an attribute to that node. (A better name from the Java platform standpoint would have been <code class="cCode">addAttribute</code>, since the attribute is not a property of the class, and since a new object is created.) </p><a name="wp80473"> </a><p class="pBody">You can also use the <code class="cCode">Document</code>'s <code class="cCode">createAttribute</code> operation to create an instance of <code class="cCode">Attribute</code>, and use the <code class="cCode">setAttributeNode</code> method to add it.</p><a name="wp65069"> </a><h4 class="pHeading3">Removing and Changing Nodes</h4><a name="wp65070"> </a><p class="pBody">To remove a node, you use its parent <code class="cCode">Node</code>'s <code class="cCode">removeChild</code> method. To change it, you can either use the parent node's <code class="cCode">replaceChild</code> operation or the node's <code class="cCode">setNodeValue</code> operation. </p><a name="wp75100"> </a><h4 class="pHeading3">Inserting Nodes</h4><a name="wp75101"> </a><p class="pBody">The important thing to remember when creating new nodes is that when you create an element node, the only data you specify is a name. In effect, that node gives you a hook to hang things on. You "hang an item on the hook" by adding to its list of child nodes. For example, you might add a text node, a CDATA node, or an attribute node. As you build, keep in mind the structure you examined in the exercises you've seen in this tutorial. Remember: Each node in the hierarchy is extremely simple, containing only one data element. </p><a name="wp65072"> </a><h3 class="pHeading2">Finishing Up</h3><a name="wp65073"> </a><p class="pBody">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! </p> </blockquote> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"> <table width="550" summary="layout" id="SummaryNotReq1"> <tr> <td align="left" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/download.html#tutorial" target="_blank">Download</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/faq.html" target="_blank">FAQ</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/history.html" target="_blank">History</a> </td> <td align="center" valign="center"><a accesskey="p" href="JAXPDOM6.html"><img id="LongDescNotReq1" src="images/PrevArrow.gif" width="26" height="26" border="0" alt="Prev" /></a><a accesskey="c" href="J2EETutorialFront.html"><img id="LongDescNotReq1" src="images/UpArrow.gif" width="26" height="26" border="0" alt="Home" /></a><a accesskey="n" href="JAXPDOM8.html"><img id="LongDescNotReq3" src="images/NextArrow.gif" width="26" height="26" border="0" alt="Next" /></a><a accesskey="i" href="J2EETutorialIX.html"></a> </td> <td align="right" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/docs/api/index.html" target="_blank">API</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/search.html" target="_blank">Search</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html" target="_blank">Feedback</a></font> </font> </td> </tr> </table> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"><p><font size="-1">All of the material in <em>The J2EE(TM) 1.4 Tutorial</em> is <a href="J2EETutorialFront2.html">copyright</a>-protected and may not be published in other workswithout express written permission from Sun Microsystems.</font> </body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -