当前位置导航:炫浪网>>网络学院>>编程开发>>JAVA教程>>JAVA网络编程

从任意数据结构生成XML解析器产生SAX事件

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


observer.jpg?http://www.xvna.com


具体实现 被观察者对象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] [2] 下一页  

相关内容
赞助商链接