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

📄 2a_echo.html

📁 XML_JAVA指南 书籍语言: 简体中文 书籍类型: 程序设计 授权方式: 免费软件 书籍大小: 377 KB
💻 HTML
📖 第 1 页 / 共 3 页
字号:
  code that invoked the parser. In the current program, that means it winds up   back at the <CODE>Throwable</CODE> exception handler at the bottom of the <CODE>main</CODE>   method. </P><P>When a start tag or end tag is encountered, the name of the tag is passed as   a String to the <CODE>startElement</CODE> or <CODE>endElement</CODE> method,   as appropriate. When a start tag is encountered, any attributes it defines are   also passed in an <A HREF=../../api/org/xml/sax/AttributeList.html><CODE>AttributeList</CODE></A>.   Characters found within the element are passed as an array of characters, along   with the number of characters (<CODE>length</CODE>) and an offset into the array   that points to the first character.</P><H3><A NAME=writing></A>Writing the Output</H3><P><A name=DIFF13></A><A href=#DIFF14><IMG src=../diffpics/oold.gif></A><STRIKE>The DocumentHandler methods throw SAXException s but that IOException s. </STRIKE><A name=DIFF13></A><A href=#DIFF14><IMG src=../diffpics/onew.gif></A><STRONG><I>The <CODE>DocumentHandler</CODE> methods throw <CODE>SAXException</CODE>s but   not <CODE>IOException</CODE>s, which can occur while writing. </STRONG></I>The <CODE>SAXException</CODE>   can wrap another exception, though, so it makes sense to do the output in a   method that takes care of the exception-handling details. Add the code highlighted   below to define an <CODE>emit</CODE> method that does that:</P><BLOCKQUOTE>   <PRE>public void characters (char buf [], int offset, int Len)throws SAXException{}<B>private void emit (String s)throws SAXException{    try {        out.write (s);        out.flush ();    } catch (IOException e) {        throw new SAXException ("I/O error", e);    }}</B>...</PRE></BLOCKQUOTE><P>When emit is called, any <A name=DIFF14></A><A href=#DIFF15><IMG src=../diffpics/oold.gif></A><STRIKE>IO </STRIKE><A name=DIFF14></A><A href=#DIFF15><IMG src=../diffpics/onew.gif></A><STRONG><I>I/O </STRONG></I>error is wrapped in <CODE>SAXException</CODE>   along with a message that identifies it. That exception is then thrown back   to the SAX parser. You'll learn more about SAX exceptions later on. For now,   keep in mind that <CODE>emit</CODE> is a small method that handles the string   output. (You'll see it called a lot in the code ahead.)</P><H4></H4><H3><A NAME=spacing></A>Spacing the Output</H3><P>There is one last bit of infrastructure we need before doing some real processing.   Add the code highlighted below to define an <CODE>nl</CODE> method that writes   the kind of line-ending character used by the current system:</P><PRE>    private void emit (String s)    ...    }  <B>    private void nl ()    throws SAXException    {        String lineEnd =  System.getProperty("line.separator");        try {            out.write (lineEnd);               } catch (IOException e) {            throw new SAXException ("I/O error", e);        }</B>    }</PRE><BLOCKQUOTE>   <P><B>Note: </B>Although it seems like a bit of a nuisance, you will be invoking     <CODE>nl()</CODE> many times in the code ahead. Defining it now will simplify     the code later on. It also provides a place to indent the output when we get     to that <A name=DIFF15></A><A href=#DIFF16><IMG src=../diffpics/oold.gif></A><STRIKE>later on. </STRIKE><A name=DIFF15></A><A href=#DIFF16><IMG src=../diffpics/onew.gif></A><STRONG><I>section of the tutorial.</STRONG></I></P></BLOCKQUOTE><H3><A NAME=events></A>Handling Document Events</H3><P>Finally, let's write some code that actually processes the <A HREF=../../api/org/xml/sax/DocumentHandler.html><CODE>DocumentHandler</CODE></A>   events we added methods for.</P><A name=DIFF16></A><A href=#DIFF17><IMG src=../diffpics/oold.gif></A><STRIKE>Note: The code discussed in here is in Echo02.java . </STRIKE><P> Add the code highlighted below to handle the start-document and end-document   events:</P><PRE>    public void startDocument ()    throws SAXException    {<B>        emit ("&lt;?xml version='1.0' encoding='UTF-8'?&gt;");        nl();</B>    }    public void endDocument ()    throws SAXException    {<B>        try {            nl();            out.flush ();        } catch (IOException e) {            throw new SAXException ("I/O error", e);        }</B>    }</PRE><P> Here, you are echoing an XML declaration when the parser encounters the start   of the document. Since you set up the <CODE>OutputStreamWriter</CODE> using   the UTF-8 encoding, you include that specification as part of the declaration.</P><BLOCKQUOTE>   <P><B>Note: </B>However, the IO classes don't understand the hyphenated encoding     names, so you specified &quot;UTF8&quot; rather than &quot;UTF-8&quot;.</P></BLOCKQUOTE><P>At the end of the document, you simply put out a final newline and flush the   output stream. Not much going on there. Now for the interesting stuff. Add the   code highlighted below to process the start-element and end-element events:</P><PRE>    public void startElement (String name, AttributeList attrs)    throws SAXException    {<B>        emit ("&lt;"+name);        if (attrs != null) {            for (int i = 0; i &lt; attrs.getLength (); i++) {                             emit (" ");                emit (attrs.getName(i)+"=\""+attrs.getValue (i)+"\"");            }        }        emit ("&gt;");</B>    }    public void endElement (String name)    throws SAXException    {<B>        emit ("&lt;/"+name+"&gt;");</B>    }</PRE>With this code, you echoed the element tags, including any attributes defined in the start tag. To finish this version of the program, add the code highlighted below to echo the characters the parser sees:<BR><BR><PRE>    public void characters (char buf [], int offset, int len)    throws SAXException    {<B>        String s = new String(buf, offset, len);        emit (s);</B>    }</PRE><P>Congratulations! You've just written a SAX parser application. The next step   is to compile and run it.</P><BLOCKQUOTE>   <P> <B>Note: </B>To be strictly accurate, the character handler should scan     the buffer for ampersand characters ('&') and left-angle bracket characters     ('&lt;') and replace them with the strings &quot;<CODE>&amp;amp;</CODE>&quot;     or &quot;<CODE>&amp;lt;</CODE>&quot;, as appropriate. You'll find out more     about that kind of processing when we discuss entity references in <A HREF=4_refs.html>Substituting     and Inserting Text</A>. </P></BLOCKQUOTE><H3><A NAME=compiling></A>Compiling the Program</H3><P>To compile the program you created, you'll execute the appropriate command   for your system (or use one of the command scripts mentioned below):</P><BLOCKQUOTE>   <P><B>Windows:</B></P>  <BLOCKQUOTE>     <PRE><A name=DIFF17></A><A href=#DIFF18><IMG src=../diffpics/oold.gif></A><STRIKE>javac -classpath %XML_HOME%\xml.jar;%JAVA_HOME%\lib\classes.zip Echo.java </STRIKE><A name=DIFF17></A><A href=#DIFF18><IMG src=../diffpics/onew.gif></A><STRONG><I>javac -classpath %XML_HOME%\jaxp.jar;%XML_HOME%\parser.jar Echo.java      </STRONG></I></PRE>  </BLOCKQUOTE>  <P><B>Unix:</B></P>  <BLOCKQUOTE>     <PRE><A name=DIFF18></A><A href=#DIFF19><IMG src=../diffpics/oold.gif></A><STRIKE>javac -classpath ${XML_HOME}/xml.jar:${JAVA_HOME}/lib/classes.zip Echo.java </STRIKE><A name=DIFF18></A><A href=#DIFF19><IMG src=../diffpics/onew.gif></A><STRONG><I>javac -classpath ${XML_HOME}/jaxp.jar:${XML_HOME}/parser.jar Echo.java      </STRONG></I></PRE>  </BLOCKQUOTE>  <P>where:</P>  <UL>    <LI> <CODE>XML_HOME</CODE> is where you installed the <A name=DIFF19></A><A href=#DIFF20><IMG src=../diffpics/onew.gif></A><STRONG><I>JAXP and </STRONG></I>Project X libraries.</LI>    <LI><A name=DIFF20></A><A href=#DIFF21><IMG src=../diffpics/oold.gif></A><STRIKE>JAVA_HOME is where JDK 1.1.x is installed. (This value, and the path to classes.zip , is not needed if you are using the Java 2 runtime interpreter.) </STRIKE><A name=DIFF20></A><A href=#DIFF21><IMG src=../diffpics/onew.gif></A><STRONG><I><TT>jaxp.jar</TT> contains the JAXP-specific APIs</STRONG></I></LI>    <LI><A name=DIFF21></A><A href=#DIFF22><IMG src=../diffpics/onew.gif></A><STRONG><I><TT>parser.jar</TT> contains the interfaces and classes that make up the       SAX and DOM APIs, as well as Sun's reference implementation, Project X.     </STRONG></I></LI>  </UL>  <P><A name=DIFF22></A><A href=#DIFF23><IMG src=../diffpics/onew.gif></A><STRONG><I><B>Note:</B><BR>    If you are using version 1.1 of the platform you also need to add <TT>%JAVA_HOME%\lib\classes.zip</TT>     to both the compile script and run script (below), where <CODE>JAVA_HOME</CODE>     is the location of the Java platform.</STRONG></I></P></BLOCKQUOTE><H3><A NAME=running></A>Running the Program</H3><P>To run the program, you'll once again execute the appropriate command for your   system (or use one of the command scripts mentioned below):</P><BLOCKQUOTE>   <P><B>Windows:</B></P>  <BLOCKQUOTE>     <PRE><A name=DIFF23></A><A href=#DIFF24><IMG src=../diffpics/oold.gif></A><STRIKE>java -classpath .;%XML_HOME%\xml.jar;%JAVA_HOME%\lib\classes.zip Echo slideSample.xml </STRIKE><A name=DIFF23></A><A href=#DIFF24><IMG src=../diffpics/onew.gif></A><STRONG><I>java -classpath .;%XML_HOME%\jaxp.jar;%XML_HOME%\parser.jar Echo slideSample.xml      </STRONG></I></PRE>  </BLOCKQUOTE>  <P> <B>Unix:</B></P>  <BLOCKQUOTE>     <PRE><A name=DIFF24></A><A href=#DIFF25><IMG src=../diffpics/oold.gif></A><STRIKE>java -classpath .:${XML_HOME}/xml.jar:${JAVA_HOME}/lib/classes.zip Echo slideSample.xml </STRIKE><A name=DIFF24></A><A href=#DIFF25><IMG src=../diffpics/onew.gif></A><STRONG><I>java -classpath .:${XML_HOME}/jaxp.jar:${XML_HOME}/parser.jar Echo slideSample.xml </STRONG></I></PRE>  </BLOCKQUOTE></BLOCKQUOTE><H3><A NAME=scripts></A>Command Scripts</H3><P>To make life easier, here are some command scripts you can use to compile and   run your apps as you work through this tutorial.<BR></P><BLOCKQUOTE>   <TABLE WIDTH=95% BORDER=1>    <TR>       <TD WIDTH=22%>&nbsp;</TD>      <TD WIDTH=29%><I><B>Unix</B></I></TD>      <TD WIDTH=49%><I><B>Windows</B></I></TD>    </TR>    <TR>       <TD WIDTH=22%>Scripts</TD>      <TD WIDTH=29%><CODE><A HREF=../bin/build>build</A></CODE>, <A HREF=../bin/run><CODE>run</CODE></A></TD>      <TD WIDTH=49%><CODE><A HREF=../bin/build.bat>build.bat</A></CODE>, <CODE><A HREF=../bin/run.bat>run.bat</A></CODE></TD>    </TR>    <TR>       <TD WIDTH=22%>Netscape<BR>      </TD>      <TD WIDTH=29%>Click, choose <B>File--&gt;Save As</B></TD>      <TD WIDTH=49%>Right click, choose <B><BR>        Save Link As</B>.</TD>    </TR>    <TR>       <TD WIDTH=22%>Internet<BR>        Explorer </TD>      <TD WIDTH=29%>         <DIV ALIGN=center>-/-</DIV>      </TD>      <TD WIDTH=49%>Right click, choose <B>Save Target As</B>.</TD>    </TR>  </TABLE></BLOCKQUOTE><H3><A NAME=checking></A>Checking the Output</H3><P>The program's output as stored in <A HREF=work/Echo01-01.log><CODE>Echo01-01.log</CODE></A>.   Here is part of it, showing some of its weird-looking spacing:</P><BLOCKQUOTE>   <PRE>...&lt;slideshow title="Sample Slide Show" date="Date of publication" author="Yours Truly"&gt;    &lt;slide type="all"&gt;      &lt;title&gt;Wake up to WonderWidgets!&lt;/title&gt;    &lt;/slide&gt;    ...</PRE></BLOCKQUOTE><A NAME=LexicalEventListener></A>Looking at this output, a number of questions arise. Namely, where is <A name=DIFF25></A><A href=#DIFF26><IMG src=../diffpics/oold.gif></A><STRIKE>all that </STRIKE><A name=DIFF25></A><A href=#DIFF26><IMG src=../diffpics/onew.gif></A><STRONG><I>the </STRONG></I>excess vertical whitespace coming from? And why is it that the elements are indented properly, <A name=DIFF26></A><A href=#DIFF27><IMG src=../diffpics/oold.gif></A><STRIKE>if </STRIKE><A name=DIFF26></A><A href=#DIFF27><IMG src=../diffpics/onew.gif></A><STRONG><I>when </STRONG></I>the code isn't doing it? We'll answer those questions in a moment. First, though, there are a few points to note about the output: <UL>  <LI>The comment defined at the top of the file </LI></UL><BLOCKQUOTE>   <PRE>&lt;!-- A SAMPLE set of slides --&gt;</PRE>  <P>does not appear in the listing. Comments are ignored by definition, unless     you implement a <A HREF=../../api/com/sun/xml/parser/LexicalEventListener.html><CODE>LexicalEventListener</CODE></A>     instead of a <CODE>DocumentHandler</CODE>. You'll see more about that later     on in this tutorial.</P></BLOCKQUOTE><UL>  <LI> 

⌨️ 快捷键说明

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