📄 1_read.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><!--NewPage--><html><head><title>Reading Data into a DOM</title><style type="text/css"><!----></style></head><body BGCOLOR="#ffffff"><table width="100%"> <tr> <td align=left> <ahref="index.html"><img src="../images/PreviousArrow.gif" width=26 height=26 align=bottom border=0 alt="Previous | "></a><ahref="2_anydata.html"><img src="../images/NextArrow.gif" width=26 height=25 align=top 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> 1. Generating a DOM from XML Data</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>Local Links</i></b></dt> </dl> <ul> <li><a href="5_create.html">Creating and Manipulating a DOM</a></li> <li><a href="../sax/2a_echo.html#compiling">Compiling the Program</a></li> <li><a href="../sax/2a_echo.html#running">Running the Program</a> </li> <li><a href="../sax/3_error.html">Handling Errors</a></li> <li><a href="../sax/6_val.html">Using the Validating Parser</a></li> <li><a href="6_ns.html">Using Namespaces</a></li> </ul> <dl> <dt><b><i>Exercise Links</i></b></dt> </dl> <ul> <li><a href="work/DomEcho01.java"><code>DomEcho01.java</code></a></li> <li><a href="samples/slideSample01.xml"><code>slideSample01.xml</code></a></li> <li><a href="samples/slideSample10.xml"><code>slideSample10.xml</code></a></li> <li><a href="samples/slideshow3.dtd">slideshow3.dtd</a></li> <li><a href="samples/xhtml.dtd">xhtml.dtd</a></li> <li><a href="work/DomEcho01-01.log">DomEcho01-01.log</a></li> <li><a href="work/DomEcho01-10.log">DomEcho01-10.log</a></li> </ul> <dl> <dt><b><i>API Links</i></b></dt> </dl> <ul> <li><a href="../../api/javax/xml/parsers/DocumentBuilder.html">DocumentBuilder</a></li> <li><a href="../../api/org/w3c/dom/Document.html">Document</a></li> </ul> <dl> <dt><b><i>External Links</i></b></dt> </dl> <ul> <li><a href="http://www.w3.org/TR/REC-DOM-Level-1/">Level 1 DOM specification</a></li> </ul> <p><b><i>Glossary Terms</i></b></p> <dl> <dd><a href="../glossary.html#DOM">DOM</a>, <a href="../glossary.html#namespace">namespace</a>, <a href="../glossary.html#SAX">SAX</a>, <a href="../glossary.html#URI">URI</a>, <a href="../glossary.html#validatingParser">validating parser</a> </dd> </dl> </td> </tr></table><p><b><i></i></b>In this section of the tutorial, you'll construct a Document Object Model (DOM) by reading in an existing XML file. Then you'll write it out as XML to verify that the program is working. <h3><b><a name="read"></a></b>Reading an XML Document into a DOM</h3><p><font color="#FF0000"><font color="#000000">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,</font></font> as you'll see in later in section 5 of this tutorial, <a href="5_create.html">Creating and Manipulating a DOM</a>. <p>However, the <a href="http://www.w3.org/TR/REC-DOM-Level-1/">Level 1 DOM specification</a> is silent on the subject of how to input and output. It tells you how a DOM has to operate, but does not cover methods for for reading or writing XML. As a result, you can't create a <a href="../glossary.html#DOM">DOM</a> from an existing XML file without going outside the DOM Level 1 specification.<p>The JAXP <a href="../../api/javax/xml/parsers/DocumentBuilder.html">DocumentBuilder</a> interface standardizes the solution to that problem by specifying a variety of parse methods that take either a File object, an input stream, a SAX InputSource object, or a <a href="../glossary.html#URI">URI</a>. When you invoke one of those methods, a DocumentBuilder implementation returns an <a href="../../api/org/w3c/dom/Document.html">org.w3c.dom.Document</a> object. <blockquote> <p><b>Note:</b> <br> To output the DOM, you'll utilize a feature of the reference implementation. Parsers from different manufactures may well use use mechanisms to achieve that goal.</p></blockquote><h4><b><a name="skel"></a></b>Create the Skeleton</h4><p>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><blockquote> <p><b>Note:</b> <br> The code discussed in this section is in <a href="work/DomEcho01.java"><code>DomEcho01.java</code></a>. The files it operates on are <a href="samples/slideSample01.xml"><code>slideSample01.xml</code></a> and <a href="samples/slideSample10.xml"><code>slideSample10.xml</code></a>. The processing output is in <a href="work/DomEcho01-01.log">DomEcho01-01.log</a> and <a href="work/DomEcho01-10.log">DomEcho01-10.log</a>. The slideSample10.xml file references <a href="samples/slideshow3.dtd">slideshow3.dtd</a> which, in turn, references a (very simplistic) <a href="samples/xhtml.dtd">xhtml.dtd</a>.</p></blockquote><p>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><blockquote> <pre>public class DomEcho {<br> public static void main (String argv []) { if (argv.length != 1) { System.err.println ("Usage: java DomEcho filename"); System.exit (1); } }// main}// DomEcho</pre></blockquote><h4> <b><a name="import"></a></b>Import the Required Classes</h4><p>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>javax.xml.parsers.*</code>.</p><p>Add these lines to import the JAXP APIs you'll be using:</p><blockquote> <pre><b>import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.DocumentBuilder;</b></pre></blockquote><p>Add these lines for the exceptions that can be thrown when the XML document is parsed: </p><blockquote> <p></p> <pre><b>import org.xml.sax.SAXException; import org.xml.sax.SAXParseException;</b></pre></blockquote>Add these lines to read the sample XML file and identify errors: <blockquote> <p></p> <p></p> <pre><b>import java.io.File;import java.io.IOException;</b></pre></blockquote><p>Finally, import the W3C definition for a DOM and DOM exceptions:</p><blockquote> <p></p> <p></p> <p></p> <pre><b>import org.w3c.dom.Document;import org.w3c.dom.DOMException;</b></pre> <b>Note: </b><br> DOMExceptions are only thrown when traversing or manipulating a DOM. Errors that occur during parsing are reporting using a different mechanism that is covered below.</blockquote><h4><b><a name="declare"></a></b>Declare the DOM</h4><p>The <a href="../../api/org/w3c/dom/Document.html">org.w3c.dom.Document</a> 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 is a global object here:</p><blockquote> <pre>public class DomEcho{ <b>static Document document;</b> public static void main (String argv []) {</pre></blockquote><p>It needs to be <tt>static</tt>, because you're going to you generate it's contents from the <tt>main</tt> method in a few minutes.</p><h4><b><a name="errors"></a></b>Handle Errors</h4><p>Next, put in the error handling logic. This is the same logic you saw in <a href="../sax/3_error.html">Handling Errors</a> in the SAX tutorial, so we won't go into it in detail here. The only 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 is pretty much identical.</p><blockquote> <pre>public static void main (String argv []){ if (argv.length != 1) { ... }<b> try {<br> } 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() );<br> // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace();<br> } catch (SAXException sxe) { // Error generated by this application // (or a parser-initialization error) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace();<br> } catch (IOException ioe) { // I/O error ioe.printStackTrace(); }</b><br><br>}// main </pre></blockquote><h4><b><a name="factory"></a></b>Instantiate the Factory </h4><p>Next, add the code highlighted below to obtain an instance of a factory that can give us a document builder:</p><blockquote> <pre>public static void main (String argv []){ if (argv.length != 1) { ... } <b>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();</b> try { </pre> <p> </blockquote><blockquote> <p> </blockquote><h4><b><a name="parse"></a></b>Get a Parser and Parse the File</h4>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -