选择显示字体大小

创造一种迅速而又随性的(quick and dirty)xml解释器

    xml是一种当前很受欢迎的数据格式, 它的优点在于: 人性化,自述性以及使用的方便性.但是,不幸的是,基于javaxml解释器往往太大了,比如sun的jaxp.jar 和 parser.jar 每个都达到了1.4mb. 如果你要在只有有限的内存容量的运行环境里运行你的程序,比如j2me的环境.或者说带宽很有限的运行环境里,比如applet,这些大的package不应该成为你的选择对象.
    注意:本篇的所有所需要的所有代码你可以通过此链接下载:
http://www.matrix.org.cn/down_view.asp?id=67
下面是qdparser的代码:
package qdxml;
import java.io.*;
import java.util.*;

/** quick and dirty xml parser.  this parser is, like the sax parser,
    an event based parser, but with much less functionality.  */
public class qdparser {
  private static int popmode(stack st) {
    if(!st.empty())
      return ((integer)st.pop()).intvalue();
    else
      return pre;
  }
  private final static int
    text = 1,
    entity = 2,
    open_tag = 3,
    close_tag = 4,
    start_tag = 5,
    attribute_lvalue = 6,
    attribute_equal = 9,
    attribute_rvalue = 10,
    quote = 7,
    in_tag = 8,
    single_tag = 12,
    comment = 13,
    done = 11,
    doctype = 14,
    pre = 15,
    cdata = 16;
  public static void parse(dochandler doc,reader r) throws exception {
    stack st = new stack();
    int depth = 0;
    int mode = pre;
    int c = 0;
    int quotec = '"';
    depth = 0;
    stringbuffer sb = new stringbuffer();
    stringbuffer etag = new stringbuffer();
    string tagname = null;
    string lvalue = null;
    string rvalue = null;
    hashtable attrs = null;
    st = new stack();
    doc.startdocument();
    int line=1, col=0;
    boolean eol = false;
    while((c = r.read()) != -1) {

      // we need to map \r, \r\n, and \n to \n
      // see xml spec section 2.11
      if(c == '\n' && eol) {
        eol = false;
        continue;
      } else if(eol) {
        eol = false;
      } else if(c == '\n') {
        line++;
        col=0;
      } else if(c == '\r') {
        eol = true;
        c = '\n';
        line++;
        col=0;
      } else {
        col++;
      }

      if(mode == done) {
        doc.enddocument();
        return;

      // we are between tags collecting text.
      } else if(mode == text) {
        if(c == '<') {
          st.push(new integer(mode));
          mode = start_tag;
          if(sb.length() > 0) {
            doc.text(sb.tostring());
            sb.setlength(0);
          }
        } else if(c == '&') {
          st.push(new integer(mode));
          mode = entity;
          etag.setlength(0);
        } else
          sb.append((char)c);

      // we are processing a closing tag: e.g. </foo>
      } else if(mode == close_tag) {
        if(c == '>') {
          mode = popmode(st);
          tagname = sb.tostring();
          sb.setlength(0);
          depth--;
          if(depth==0)
            mode = done;
          doc.endelement(tagname);
        } else {
          sb.append((char)c);
        }

      // we are processing cdata
      } else if(mode == cdata) {
        if(c == '>'
        && sb.tostring().endswith(&quot;]]&quot;)) {
          sb.setlength(sb.length()-2);
          doc.text(sb.tostring());
          sb.setlength(0);
          mode = popmode(st);
        } else
          sb.append((char)c);

      // we are processing a comment.  we are inside
      // the <!-- .... --> looking for the -->.
      } else if(mode == comment) {
        if(c == '>'
        && sb.tostring().endswith(&quot;--&quot;)) {
          sb.setlength(0);
          mode = popmode(st);
        } else
          sb.append((char)c);

      // we are outside the root tag element
      } else if(mode == pre) {
        if(c == '<') {
          mode = text;
          st.push(new integer(mode));
          mode = start_tag;
        }

      // we are inside one of these <? ... ?>
      // or one of these <!doctype ... >
      } else if(mode == doctype) {
        if(c == '>') {
          mode = popmode(st);
          if(mode == text) mode = pre;
        }

      // we have just seen a < and
      // are wondering what we are looking at
      // <foo>, </foo>, <!-- ... --->, etc.
      } else if(mode == start_tag) {
        mode = popmode(st);
        if(c == '/') {
          st.push(new integer(mode));
          mode = close_tag;
        } else if (c == '?') {
          mode = doctype;
        } else {
          st.push(new integer(mode));
          mode = open_tag;
          tagname = null;
          attrs = new hashtable();
          sb.append((char)c);
        }

      // we are processing an entity, e.g. <, &raquo;, etc.
      } else if(mode == entity) {
        if(c == ';') {
          mode = popmode(st);
          string cent = etag.tostring();
          etag.setlength(0);
          if(cent.equals(&quot;lt&quot;))
            sb.append('<');
          else if(cent.equals(&quot;gt&quot;))
            sb.append('>');
          else if(cent.equals(&quot;amp&quot;))
            sb.append('&');
          else if(cent.equals(&quot;quot&quot;))
            sb.append('&quot;');
          else if(cent.equals(&quot;apos&quot;))
            sb.append('\'');
          // could parse hex entities if we wanted to
          //else if(cent.startswith(&quot;#x&quot;))
            //sb.append((char)integer.parseint(cent.substring(2),16));
          else if(cent.startswith(&quot;#&quot;))
            sb.append((char)integer.parseint(cent.substring(1)));
          // insert custom entity definitions here
          else
            exc(&quot;unknown entity: &&quot;+cent+&quot;;&quot;,line,col);
        } else {
          etag.append((char)c);
        }

      // we have just seen something like this:
      // <foo a=&quot;b&quot;/
      // and are looking for the final >.
      } else if(mode == single_tag) {
        if(tagname == null)
          tagname = sb.tostring();
        if(c != '>')
          exc(&quot;expected > for tag: <&quot;+tagname+&quot;/>&quot;,line,col);
        doc.startelement(tagname,attrs);
        doc.endelement(tagname);
        if(depth==0) {
          doc.enddocument();
          return;
        }
        sb.setlength(0);
        attrs = new hashtable();
        tagname = null;
        mode = popmode(st);

      // we are processing something
      // like this <foo ... >.  it could
      // still be a <!-- ... --> or something.
      } else if(mode == open_tag) {
        if(c == '>') {
          if(tagname == null)
            tagname = sb.tostring();
          sb.setlength(0);
          depth++;
          doc.startelement(tagname,attrs);
          tagname = null;
          attrs = new hashtable();
          mode = popmode(st);
        } else if(c == '/') {
          mode = single_tag;
        } else if(c == '-' && sb.tostring().equals(&quot;!-&quot;)) {
          mode = comment;
        } else if(c == '[' && sb.tostring().equals(&quot;![cdata&quot;)) {
          mode = cdata;
          sb.setlength(0);
        } else if(c == 'e' && sb.tostring().equals(&quot;!doctyp&quot;)) {
          sb.setlength(0);
          mode = doctype;
        } else if(character.iswhitespace((char)c)) {
          tagname = sb.tostring();
          sb.setlength(0);
          mode = in_tag;
        } else {
          sb.append((char)c);
        }

      // we are processing the quoted right-hand side
      // of an element's attribute.
      } else if(mode == quote) {
        if(c == quotec) {
          rvalue = sb.tostring();
          sb.setlength(0);
          attrs.put(lvalue,rvalue);
          mode = in_tag;
        // see section the xml spec, section 3.3.3
        // on normalization processing.
        } else if(&quot; \r\n\u0009&quot;.indexof(c)>=0) {
          sb.append(' ');
        } else if(c == '&') {
          st.push(new integer(mode));
          mode = entity;
          etag.setlength(0);
        } else {
          sb.append((char)c);
        }

      } else if(mode == attribute_rvalue) {
        if(c == '&quot;' c == '\'') {
          quotec = c;
          mode = quote;
        } else if(character.iswhitespace((char)c)) {
          ;
        } else {
          exc(&quot;error in attribute processing&quot;,line,col);
        }

      } else if(mode == attribute_lvalue) {
        if(character.iswhitespace((char)c)) {
          lvalue = sb.tostring();
          sb.setlength(0);
          mode = attribute_equal;
        } else if(c == '=') {
          lvalue = sb.tostring();
          sb.setlength(0);
          mode = attribute_rvalue;
        } else {
          sb.append((char)c);
        }

      } else if(mode == attribute_equal) {
        if(c == '=') {
          mode = attribute_rvalue;
        } else if(character.iswhitespace((char)c)) {
          ;
        } else {
          exc(&quot;error in attribute processing.&quot;,line,col);
        }

      } else if(mode == in_tag) {
        if(c == '>') {
          mode = popmode(st);
          doc.startelement(tagname,attrs);
          depth++;
          tagname = null;
          attrs = new hashtable();
        } else if(c == '/') {
          mode = single_tag;
        } else if(character.iswhitespace((char)c)) {
          ;
        } else {
          mode = attribute_lvalue;
          sb.append((char)c);
        }
      }
    }
    if(mode == done)
      doc.enddocument();
    else
      exc(&quot;missing end tag&quot;,line,col);
  }
  private static void exc(string s,int line,int col)
    throws exception
  {
    throw new exception(s+&quot; near line &quot;+line+&quot;, column &quot;+col);
  }
}
    为何不使用sax?
    你可以实现仅还有有限功能的sax接口, 当遇到某些东西你不需要的时候,抛出notimplemented异常.
     无庸置疑地, 这样你可以开发出小于jaxp.jar和parser.jar的类.但是,你可以通过定义自己的类来达到更加小的size.实际上,我们这里定义的类将会比sax接口还要小很多.
      我们的迅速而又随性的xml解释器有点类似于sax. 类似于sax解释器,它能够让你实现接口从而可以捕获并处理与属性和开始/结束标签. 你们如果已经使用过sax,你们会发现它很熟悉.
      
       限制的xml功能
       很多人都喜欢xml样式的简单的,自述的,文本式的数据格式. 他们希望很容易地获取当中地元素,属性以及属性的值. 顺着这种思想,让我们来考虑一下哪些功能使我们必须的.
       我们的简单的解释器只有一个类:qdparser 与一个接口:dochandler. qdparser拥有一个public的静态方法-parse(dochandler,reader)&mdash;我们把它定义成一个有限状态自动机.
        我们的简单的解释器会把dtd <!doctype> 与 <?xml version=&quot;1.0&quot;?>仅仅看成是注释,所以,他们不会造成混乱,他们的内容对我们来说也是无用的.
         因为我们不能处理doctype, 我们的解释器不能读取自定义的实体.只有这些是作为标准可用的: &, <, >, &apos;, and &quot;.如果你觉得这些不够,那么,可以自己插入代码来扩展自己的定义.或者你也可以再递交给qdparser之前先预处理你的xml文件.
          我们的简单的解释器也不支持条件选择:比如, <![include[ ... ]]> or <![ignore[ ... ]]>.因为我们不能通过doctype自定义实体,这个功能对我们来说也是毫无意义的.我们可以在数据传递到我们的有限容量处理设备之前解决这个条件选择的问题.
           因为我们的解释器不会处理任何属性的声明,xml规范要求我们把所有的数据类型都看成是cdata,这样,我们可以使用java.util.hashtable来代替org.xml.sax.attributelist来存储一个元素的属性列表.在hashtable里,我们仅仅有名字/值对应的信息,因为我们不需要gettype()因为此时,无论如何都会返回cdata.
      缺少属性声明会导致一些其他的结果,比如,解释器不提供默认的属性值.还有,我们也不能通过声明nmtokens来自动减少空闲空间.然后,这些都可以在我们准备或者生成xml文件的时候处理.这些额外的代码都可以放到使用我们的parser的程序外部去.
       实际上,缺少的功能都可以在准备xml文件的时候补偿回来,这样,你就可以分担很多功能-我们的parser失去的功能 给准备xml文件的时候处理.
        
解释器功能
既然讨论了这么多我们的parser不能做到的事情,那什么是它可以做到的呢?
1.        它能识别所有元素的开始和结束标签.
2.        它能够列出所有属性.
3.        它能够识别<[cdata[ ... ]]> 这种结构
4.        它能够识别标准实体: &, <, >, &quot;, and &apos,与数字实体.
5.        它能将输入的\r\n和\r to \n看成是一行的结束,符合xml规范里的2.11.
        这个解释器仅仅带有很有限的错误检查,当遇到错误的文法的时候,就会抛出异常,比如遇到它不能识别的实体.

        如何使用这个解释器
        使用我们这个quick and dirty解释器是很简单的,首先,实现dochandler的接口,然后就可以解释一个xml文件:
         dochandler doc = new mydochandler();
qdparser.parse(doc,new filereader(&quot;config.xml&quot;));
         源代码包含有两个实现了全部dochandler接口的例子,第一个叫
reporter,仅仅是输出它读到的内容,你可以用例子里的xml文件:config.xml来测
试这个例子.
第二个例子conf稍微复杂,conf实现更新已经存在的驻扎的内存的数据.
conf通过java.lang.reflect来定位config.xml里定义的fields和对象.如果你运行这个程序,它会告诉你哪些对象在更新与如何更新.如果遇到要求更新不存在的fields,它会报出错信息.

         修改这个package
          你可以修改这个类来使之适合你自己的使用,你可以添加你自定义的实体定义-在qdparser.java的第180行.
           你也可以添加我排除的功能到这个解释器的有限状态机里面去.这个是比较容易实现的,因为原有的代码量很少.
          
           keep it small
           qdparser只有3kb大小当你编译之后或者打包到jar文件里去.源代码也只有300行,还包括注释在内,这个对很多小容量的设备来说是有效的,可以保持符合xml的标准,并实现基本的功能.


matrix开源技术经javaworld授权翻译并发布.
如果你对此文章有任何看法或建议,请到matrix论坛发表您的意见.
注明: 如果对matrix的翻译文章系列感兴趣,请点击oreilly和javaworld文章翻译计划查看详细情况
您也可以点击-chris查看翻译作者的详细信息.
        
          
      

      


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons