Chinaunix首页 | 论坛 | 博客
  • 博客访问: 273963
  • 博文数量: 757
  • 博客积分: 40040
  • 博客等级: 大将
  • 技术积分: 4935
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-09 12:37
文章分类

全部博文(757)

文章存档

2011年(1)

2008年(756)

我的朋友

分类:

2008-09-09 12:41:04

    在j2ee1.4标准教材里看到一个很有趣的例子,从任意数据结构生成XML解析器产生SAX事件.数据结构可以是文本文件,PDF格式文档等.关键是自己解析这些数据源.另外一个有意思的地方是观察者模式的应用.所以就粗糙的改了一下并完整到可以测试运行.观察者模式简略UML图:


observer.jpg


具体实现 被观察者对象ParseXMLSubject类:
package test;

import java.io.*;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.*;

public class ParseXMLSubject implements XMLReader {
    ContentHandler handler;

    String nsu = "";
    Attributes atts = new AttributesImpl();
    String rootElement = "addressbook";
    String indent = "\n    ";

    public ParseXMLSubject(){

    }

    public ContentHandler getContentHandler() {
        return handler;
    }

    public void parse(InputSource input) throws IOException, SAXException {
        try {
            // Get an efficient reader for the file
            java.io.Reader r = input.getCharacterStream();
            BufferedReader br = new BufferedReader(r);

            // Read the file and display it's contents.
            String line = br.readLine();

            while (null != (line = br.readLine())) {
                if (line.startsWith("email:")) {
                    break;
                }
            }

            if (handler == null) {
                throw new SAXException("No content handler");
            }

            // Note:
            // We're ignoring setDocumentLocator(), as well
            handler.startDocument();
            handler.startElement(nsu, rootElement, rootElement, atts);

            output("email",  line);
            line = br.readLine();
            output("html", line);
            line = br.readLine();
            output("firstname",  line);
            line = br.readLine();
            output("lastname", line);
            line = br.readLine();
            output("work",  line);
            line = br.readLine();
            output("home", line);
            line = br.readLine();
            output("fax",  line);
            line = br.readLine();
            output("pager", line);
            line = br.readLine();
            output("cell",  line);
            handler.ignorableWhitespace("\n".toCharArray(), 0, // start index
                                        1 // length
                    );
            handler.endElement(nsu, rootElement, rootElement);
            handler.endDocument();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void parse(String systemId) throws IOException, SAXException {
    }


    public DTDHandler getDTDHandler() {
        return null;
    }


    public EntityResolver getEntityResolver() {
        return null;
    }

 

[1]  

【责编:Kittoy】

--------------------next---------------------

阅读(124) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~