📄 jaxpdom3.html
字号:
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Reading XML Data into a DOM</title> <link rel="StyleSheet" href="document.css" type="text/css" media="all" /> <link rel="StyleSheet" href="catalog.css" type="text/css" media="all" /> <link rel="Table of Contents" href="J2EETutorialTOC.html" /> <link rel="Previous" href="JAXPDOM2.html" /> <link rel="Next" href="JAXPDOM4.html" /> <link rel="Index" href="J2EETutorialIX.html" /> </head> <body> <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="JAXPDOM2.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="JAXPDOM4.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"> <blockquote><a name="wp68274"> </a><h2 class="pHeading1">Reading XML Data into a DOM</h2><a name="wp67730"> </a><p class="pBody">In this section of the tutorial, you'll construct a Document Object Model (DOM) by reading in an existing XML file. In the following sections, you'll see how to display the XML in a Swing tree component and practice manipulating the DOM. </p><hr><a name="wp64044"> </a><p class="pNote">Note: In the next part of the tutorial, <a href="JAXPXSLT.html#wp68287">XML Stylesheet Language for Transformations</a>, you'll see how to write out a DOM as an XML file. (You'll also see how to convert an existing data file into XML with relative ease.) </p><hr><a name="wp64046"> </a><h3 class="pHeading2">Creating the Program</h3><a name="wp64047"> </a><p class="pBody">The Document Object Model (DOM) provides APIs that let you create nodes, modify them, delete and rearrange them. So it is relatively easy to create a DOM, as you'll see in later in section 5 of this tutorial, <a href="JAXPDOM7.html#wp65002">Creating and Manipulating a DOM</a>. </p><a name="wp64051"> </a><p class="pBody">Before you try to create a DOM, however, it is helpful to understand how a DOM is structured. This series of exercises will make DOM internals visible by displaying them in a Swing <code class="cCode">JTree</code>. </p><a name="wp64053"> </a><h4 class="pHeading3">Create the Skeleton</h4><a name="wp64054"> </a><p class="pBody">Now that you've had a quick overview of how to create a DOM, let's build a simple program to read an XML document into a DOM then write it back out again. </p><hr><a name="wp64055"> </a><p class="pNote">Note: The code discussed in this section is in <code class="cCode"><a href="../examples/jaxp/dom/samples/DomEcho01.java" target="_blank">DomEcho01.java</a></code>. The file it operates on is<code class="cCode"><a href="../examples/jaxp/dom/samples/slideSample01.xml" target="_blank"> slideSample01.xml</a></code>. (The browsable version is<code class="cCode"><a href="../examples/jaxp/dom/samples/slideSample01-xml.html" target="_blank"> slideSample01-xml.html</a></code>.) </p><hr><a name="wp64056"> </a><p class="pBody">Start with a normal basic logic for an app, and check to make sure that an argument has been supplied on the command line:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class DomEcho { public static void main(String argv[]) { if (argv.length != 1) { System.err.println( "Usage: java DomEcho filename"); System.exit(1); } }// main}// DomEcho<a name="wp66275"> </a></pre></div><a name="wp64059"> </a><h4 class="pHeading3">Import the Required Classes</h4><a name="wp64060"> </a><p class="pBody">In this section, you're going to see all the classes individually named. That's so you can see where each class comes from when you want to reference the API documentation. In your own apps, you may well want to replace import statements like those below with the shorter form: <code class="cCode">javax.xml.parsers.*</code>.</p><a name="wp64061"> </a><p class="pBody">Add these lines to import the JAXP APIs you'll be using:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException;<a name="wp64062"> </a></pre></div><a name="wp64063"> </a><p class="pBody">Add these lines for the exceptions that can be thrown when the XML document is parsed: </p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">import org.xml.sax.SAXException; import org.xml.sax.SAXParseException;<a name="wp64064"> </a></pre></div><a name="wp64065"> </a><p class="pBody">Add these lines to read the sample XML file and identify errors: </p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">import java.io.File;import java.io.IOException;<a name="wp64066"> </a></pre></div><a name="wp64067"> </a><p class="pBody">Finally, import the W3C definition for a DOM and DOM exceptions:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">import org.w3c.dom.Document;import org.w3c.dom.DOMException;<a name="wp64068"> </a></pre></div><hr><a name="wp64069"> </a><p class="pNote">Note: A <code class="cCode">DOMException</code> is only thrown when traversing or manipulating a DOM. Errors that occur during parsing are reporting using a different mechanism that is covered below.</p><hr><a name="wp64071"> </a><h4 class="pHeading3">Declare the DOM</h4><a name="wp64072"> </a><p class="pBody">The <code class="cCode">org.w3c.dom.Document</code> class is the W3C name for a Document Object Model (DOM). Whether you parse an XML document or create one, a Document instance will result. We'll want to reference that object from another method later on in the tutorial, so define it as a global object here:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class DomEcho{ <code class="cCodeBold"> static Document document;</code> public static void main(String argv[]) {<a name="wp64073"> </a></pre></div><a name="wp64074"> </a><p class="pBody">It needs to be <code class="cCode">static</code>, because you're going to generate its contents from the <code class="cCode">main</code> method in a few minutes.</p><a name="wp64076"> </a><h4 class="pHeading3">Handle Errors</h4><a name="wp64077"> </a><p class="pBody">Next, put in the error handling logic. This logic is basically the same as the code you saw in <a href="JAXPSAX5.html#wp64579">Handling Errors with the Nonvalidating Parser</a> in the SAX tutorial, so we won't go into it in detail here. The major point worth noting is that a JAXP-conformant document builder is required to report SAX exceptions when it has trouble parsing the XML document. The DOM parser does not have to actually use a SAX parser internally, but since the SAX standard was already there, it seemed to make sense to use it for reporting errors. As a result, the error-handling code for DOM and SAX applications are very similar:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public static void main(String argv[]){ if (argv.length != 1) { ... } <code class="cCodeBold">try {} catch (SAXParseException spe) { // Error generated by the parser System.out.println("\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.out.println(" " + spe.getMessage() ); // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace(); } catch (SAXException sxe) { // Error generated during parsing Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace();</code> } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -