⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 2a_echo.html

📁 XML_JAVA指南 书籍语言: 简体中文 书籍类型: 程序设计 授权方式: 免费软件 书籍大小: 377 KB
💻 HTML
📖 第 1 页 / 共 3 页
字号:
<!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><HR><B>HtmlDiff: </B>Here is the <A href=#DIFF0>first difference.</A> There are 28 differences. <IMG src=../diffpics/oold.gif><STRIKE>is old.</STRIKE><IMG src=../diffpics/onew.gif><STRONG><I> is new. </I></STRONG><HR><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><A name=DIFF0></A><A href=#DIFF1><IMG src=../diffpics/onew.gif></A><STRONG><I>1. </STRONG></I>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/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/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 &quot;Hello World&quot; 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[])    <A name=DIFF1></A><A href=#DIFF2><IMG src=../diffpics/oold.gif></A><STRIKE>throws IOException </STRIKE>{    }}</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. <A name=DIFF2></A><A href=#DIFF3><IMG src=../diffpics/oold.gif></A><STRIKE>We need command-line arguments so we can tell the app which file to echo, and we're going to write to System.out , so we need to be prepared to throw any IO Exception we can't handle. </STRIKE><A name=DIFF2></A><A href=#DIFF3><IMG src=../diffpics/onew.gif></A><STRONG><I>And we need   command-line arguments so we can tell the app which file to echo.</STRONG></I></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.*;<A name=DIFF3></A><A href=#DIFF4><IMG src=../diffpics/oold.gif></A><STRIKE>import org.xml.sax.helpers.ParserFactory; import com.sun.xml.parser.Resolver; </STRIKE><A name=DIFF3></A><A href=#DIFF4><IMG src=../diffpics/onew.gif></A><STRONG><I>import javax.xml.parsers.SAXParserFactory;  import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;</STRONG></I></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 <A name=DIFF4></A><A href=#DIFF5><IMG src=../diffpics/oold.gif></A><STRIKE>ParserFactory </STRIKE><A name=DIFF4></A><A href=#DIFF5><IMG src=../diffpics/onew.gif></A><STRONG><I>SAXParserFactory   </STRONG></I>class creates the instance we use. <A name=DIFF5></A><A href=#DIFF6><IMG src=../diffpics/oold.gif></A><STRIKE>Finally, the Resolver class is needed to create an input source for the parser to operate on. </STRIKE><A name=DIFF5></A><A href=#DIFF6><IMG src=../diffpics/onew.gif></A><STRONG><I>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. </STRONG></I></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 [])    <A name=DIFF6></A><A href=#DIFF7><IMG src=../diffpics/oold.gif></A><STRIKE>throws IOException </STRIKE>{<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>    <A name=DIFF7></A><A href=#DIFF8><IMG src=../diffpics/oold.gif></A><STRIKE>public static void main (String argv []) throws IOException { InputSource input; if (argv.length != 1) { System.err.println ("Usage: </STRIKE><A name=DIFF7></A><A href=#DIFF8><IMG src=../diffpics/onew.gif></A><STRONG><I>public static void main (String argv [])    {        if (argv.length != 1) {            System.err.println ("Usage: </STRONG></I>cmd filename");            System.exit (1);        <A name=DIFF8></A><A href=#DIFF9><IMG src=../diffpics/onew.gif></A><STRONG><I>}<B>        // Use the default (non-validating) parser        SAXParserFactory factory = SAXParserFactory.newInstance();</STRONG></I><A name=DIFF8></A><A href=#DIFF9><IMG src=../diffpics/oold.gif></A><STRIKE>} </STRIKE></B>        try {            // Set up output stream            out = new OutputStreamWriter (System.out, "UTF8");<A name=DIFF9></A><A href=#DIFF10><IMG src=../diffpics/oold.gif></A><STRIKE>// Turn the filename into an XML input source input = Resolver.createInputSource (new File (argv [0])); // Get an instance of the non-validating parser. Parser parser; parser = ParserFactory.makeParser ("com.sun.xml.parser.Parser"); parser.setDocumentHandler ( new Echo() ); // Parse the input parser.parse (input); </STRIKE><A name=DIFF9></A><A href=#DIFF10><IMG src=../diffpics/onew.gif></A><STRONG><I><B>            // Parse the input             SAXParser saxParser = factory.newSAXParser();            saxParser.parse( new File(argv [0]), new Echo() );</STRONG></I></B>        } catch (Throwable t) {            t.printStackTrace ();        }        System.exit (0);    }</PRE><P><A name=DIFF10></A><A href=#DIFF11><IMG src=../diffpics/oold.gif></A><STRIKE>With these additions, you created an org.xml.sax.InputSource object for the SAX parser to operate on. You then used the com.sun.xml.parser.Resolver class to create an InputSource from a java.io.File object. After that you used the ParserFactory to get an instance of the parser, specifying the full-qualified classname. (You could also have used the no-argument version of makeParser() , which uses the com.sun.xml.parser system property, if it is defined.) </STRIKE><A name=DIFF10></A><A href=#DIFF11><IMG src=../diffpics/onew.gif></A><STRONG><I>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.</STRONG></I></P><BLOCKQUOTE>   <P><A name=DIFF11></A><A href=#DIFF12><IMG src=../diffpics/oold.gif></A><STRIKE>In the last two lines of code you entered, you gave the parser an instance of this class to use as a DocumentHandler and told the parser to go to work on the InputSource object. </STRIKE><A name=DIFF11></A><A href=#DIFF12><IMG src=../diffpics/onew.gif></A><STRONG><I><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.</STRONG></I></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><A name=DIFF12></A><A href=#DIFF13><IMG src=../diffpics/onew.gif></A><STRONG><I><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/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.</STRONG></I></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   to throw a <A HREF=../../api/org/xml/sax/SAXException.html><CODE>SAXException</CODE></A>.   An exception thrown here is sent back to the parser, which sends it on to the 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -