📄 2a_echo.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>Echoing an XML File with the SAX Parser</title>
<style type="text/css">
</style></head>
<body BGCOLOR="#ffffff">
<table width="100%">
<tr>
<td align=left> <a href="1_write.html"><img src="../images/PreviousArrow.gif" width=26 height=26 align=top border=0 alt="Previous | "></a><a
href="2b_echo.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"><img
src="../images/xml_TOC.gif" width=26 height=26 align=top border=0 alt="TOC | "></a><a href="../index.html"><img
src="../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="../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>
<h2>1. Echoing an XML File with the SAX Parser</h2>
<table width="35%" 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="../overview/3_apis.html">An Overview of the Java XML APIs</a></li>
<li><a href="../info/encodings.html">Java's Encoding Schemes</a></li>
<li><a href="3_error.html">Handling Errors with the Non-Validating Parser</a></li>
<li><a href="4_refs.html">Substituting and Inserting Text</a></li>
</ul>
<p><b><i>Examples</i></b></p>
<ul>
<li><a href="../bin/build">build</a>, <a href="../bin/run">run</a></li>
<li> <a href="../bin/build.bat">build.bat</a>, <a href="../bin/run.bat">run.bat</a></li>
<li><a href="work/Echo01.java">Echo01.java</a> </li>
<li><a href="samples/slideSample01.xml">slideSample01.xml</a></li>
<li><a href="work/Echo01-01.log">Echo01-01.log</a></li>
<li><a href="work/Echo02.java">Echo02.java</a></li>
<li><a href="work/Echo02-01.log">Echo02-01.log</a></li>
<li><a href="work/Echo03.java">Echo03.java</a></li>
<li><a href="work/Echo03-01.log">Echo03-01.log</a></li>
</ul>
<p><b><i>API References</i></b></p>
<ul>
<li><a href="../../api/org/xml/sax/HandlerBase.html">HandlerBase</a></li>
<li><a href="../../api/org/xml/sax/package-summary.html">org.xml.sax</a></li>
<li><a href="../../api/org/xml/sax/InputSource.html">org.xml.sax.InputSource</a></li>
<li><a href="../../api/internal/com/sun/xml/parser/Resolver.html">com.sun.xml.parser.Resolver</a></li>
<li><a href="../../api/org/xml/sax/DocumentHandler.html">DocumentHandler</a></li>
<li><a href="../../api/internal/com/sun/xml/parser/LexicalEventListener.html">LexicalEventListener</a>
</li>
<li><a href="../../api/org/xml/sax/SAXException.html">SAXException</a></li>
<li><a href="../../api/org/xml/sax/AttributeList.html">AttributeList</a></li>
</ul>
<p><b><i>Glossary Terms</i></b></p>
<dl>
<dd><a href="../glossary.html#DOM">DOM</a></dd>
</dl>
</td>
</tr>
</table>
<p>In real life, you are going to have little need to echo an XML file with a
SAX parser. Usually, you'll want to process the data in some way in order to
do something useful with it. (If you want to echo it, it's easier to build a
<a href="../glossary.html#DOM">DOM</a> tree and use its built-in printing functions.)
But echoing an XML structure is a great way to se the SAX parser in action.
In this exercise, you'll set echo SAX parser events to <code>System.out</code>.
<p>Consider this the "Hello World" version of an XML-processing program.
It shows you how to use the SAX parser to get at the data, and then echoes it
to show you what you've got.
<blockquote> <b>Note:</b> <br>
The code discussed in this section is in <a href="work/Echo01.java"><code>Echo01.java</code></a>.
The file it operates on is <a href="samples/slideSample01.xml"><code>slideSample01.xml</code></a>.</blockquote>
<h3><a name="skeleton"></a>Create the Skeleton</h3>
<p>Start by creating a file named<b> </b><code>Echo.java</code> and enter the
skeleton for the application:</p>
<blockquote>
<pre>public class Echo extends HandlerBase
{
public static void main (String argv[])
{
}
}</pre>
</blockquote>
<p>This class extends <a href="../../api/org/xml/sax/HandlerBase.html"><code>HandlerBase</code></a>,
which implements all of the interfaces we discussed in <a href="../overview/3_apis.html">An
Overview of the Java XML APIs</a>. That lets us override the methods we care
about and default the rest.</p>
<p>Since we're going to run it standalone, we need a main method. And we need
command-line arguments so we can tell the app which file to echo.</p>
<h3><a name="import"></a>Import the Classes We Need</h3>
<p>Next, add the import statements for the classes the app will use:</p>
<blockquote>
<pre><b>import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
</b>public class Echo extends HandlerBase
{
...
</pre>
</blockquote>
<p>The classes in <code>java.io</code>, of course, are needed to do output. The
<a href="../../api/org/xml/sax/package-summary.html"><code>org.xml.sax</code></a>
package defines all the interfaces we use for the SAX parser. The SAXParserFactory
class creates the instance we use. It throws a ParserConfigurationException
if it is unable to produce a parser that matches the specified configuration
of options. (You'll see more about the configuration options later.) Finally,
the SAXParser is what the factory returns for parsing. </p>
<h3><a name="io"></a>Setting up for I/O</h3>
The first order of business is to process the command line argument, get the name
of the file to echo, and set up the output stream. Add the text highlighted below
to take care of those tasks and do a bit of additional housekeeping:
<pre> public static void main (String argv [])
{
<b> if (argv.length != 1) {
System.err.println ("Usage: cmd filename");
System.exit (1);
}
try {
// Set up output stream
out = new OutputStreamWriter (System.out, "UTF8");
} catch (Throwable t) {
t.printStackTrace ();
}
System.exit (0);
</b> }
<br> <b>static private Writer out;</b>
</pre>
<p><a name="encoding"></a>When we create the output stream writer, we are selecting
the UTF-8 character encoding. We could also have chosen US-ASCII, or UTF-16,
which the Java platform also supports. For more information on these character
sets, see <a href="../info/encodings.html">Java's Encoding Schemes</a>.</p>
<p></p>
<h3><a name="parser"></a>Setting up the Parser</h3>
<p>Now (at last) you're ready to set up the parser. Add the text highlighted below
to set it up and get it started:</p>
<pre> public static void main (String argv [])
{
if (argv.length != 1) {
System.err.println ("Usage: cmd filename");
System.exit (1);
}
<b> // Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
</b> try {
// Set up output stream
out = new OutputStreamWriter (System.out, "UTF8");
<b>
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(argv [0]), new Echo() );
</b> } catch (Throwable t) {
t.printStackTrace ();
}
System.exit (0);
}
</pre>
<p>With these lines of code, you created a <code>SAXParserFactory</code> instance,
as determined by the setting of the <code>javax.xml.parsers.SAXParserFactory</code>
system property. You then got a parser from the factor and gave the parser an
instance of this class to handle the parsing events, telling it which input
file to process.</p>
<blockquote>
<p><b>Note:</b><br>
The <tt>javax.xml.parsers.</tt>SAXParser class is a wrapper that defines a
number of convenience methods. It wraps the (somewhat-less friendly) <tt>org.xml.sax.</tt>Parser
object. If needed, you can obtain that parser using the SAXParser's <tt>getParser()</tt>
method.</p>
</blockquote>
<p>For now, you are simply catching any exception that the parser might throw.
You'll learn more about error processing in a later section of the tutorial,
<a href="3_error.html">Handling Errors with the Nonvalidating Parser</a>.</p>
<blockquote>
<p><b>Note:</b><br>
The <tt>parse</tt> method that operates on File objects is a convenience method.
Under the covers, it creates an <a href="../../api/org/xml/sax/InputSource.html"><code>org.xml.sax.InputSource</code></a>
object for the SAX parser to operate on. To do that, it uses a static method
in the <a href="../../api/internal/com/sun/xml/parser/Resolver.html"><code>com.sun.xml.parser.Resolver</code></a>
class to create an InputSource from a <code>java.io.File</code> object. You
could do that, too, but the convenience method makes things easier.</p>
</blockquote>
<p></p>
<h3><a name="DocumentHandler"></a>Implementing the DocumentHandler Interface</h3>
<p>The most important interface for our current purposes is the <a href="../../api/org/xml/sax/DocumentHandler.html"><code>DocumentHandler</code></a>
interface. That interface requires a number of methods that the SAX parser invokes
in response to different parsing events. For now, we are concerned with only
five of them: <code>startDocument</code>, <code>endDocument</code>, <code>startElement</code>,
<code>endElement</code>, and <code>characters</code>. Enter the code highlighted
below to set up methods to handle those events:</p>
<pre>
...
static private Writer out;
</pre>
<p></p>
<pre> <b>public void startDocument ()
throws SAXException
{
}
public void endDocument ()
throws SAXException
{
}
public void startElement (String name, AttributeList attrs)
throws SAXException
{
}
public void endElement (String name)
throws SAXException
{
}
public void characters (char buf [], int offset, int len)
throws SAXException
{
}
</b>...</pre>
<p><a name="SAXExceptionThrown"></a>Each of these methods is required by the interface
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -