新书推介:《语义网技术体系》
作者:瞿裕忠,胡伟,程龚
   XML论坛     W3CHINA.ORG讨论区     计算机科学论坛     SOAChina论坛     Blog     开放翻译计划     新浪微博  
 
  • 首页
  • 登录
  • 注册
  • 软件下载
  • 资料下载
  • 核心成员
  • 帮助
  •   Add to Google

    >> 本版讨论DOM, SAX, XPath等。
    [返回] 中文XML论坛 - 专业的XML技术讨论区XML.ORG.CN讨论区 - XML技术『 DOM/SAX/XPath 』 → [原创]用dom写得的一个留言本程序 查看新帖用户列表

      发表一个新主题  发表一个新投票  回复主题  (订阅本版) 您是本帖的第 8955 个阅读者浏览上一篇主题  刷新本主题   树形显示贴子 浏览下一篇主题
     * 贴子主题: [原创]用dom写得的一个留言本程序 举报  打印  推荐  IE收藏夹 
       本主题类别:     
     绝情酷哥 帅哥哟,离线,有人找我吗?
      
      
      等级:大一(高数修炼中)
      文章:2
      积分:121
      门派:XML.ORG.CN
      注册:2004/7/31

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给绝情酷哥发送一个短消息 把绝情酷哥加入好友 查看绝情酷哥的个人资料 搜索绝情酷哥在『 DOM/SAX/XPath 』的所有贴子 引用回复这个贴子 回复这个贴子 查看绝情酷哥的博客楼主
    发贴心情 [原创]用dom写得的一个留言本程序

    //guestbook.xml文件设计如下
    <?xml version="1.0" encoding="GB2312"?>
    <cucuchen>
    <guestbook>
    <data>
    <user id="1">
    <url>http://alas520.126.com</url>
    <ip>192.168.1.223</ip>
    <time>2004-07-28</time>
    <qq>43767528</qq>
    <email>xch@linewell.com</email>
    <name>xiechuanhai</name>
    <photo>test.jpg</photo>
    <content>小谢测试一下修改呵</content>
    </user>
    </data>
    </guestbook>
    </cucuchen>


    //XmlFactory.java文件
    package com.cucu.xml.db;

    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;


    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.*;
    import java.io.IOException;
    import java.io.File;
    import java.util.Properties;

    /**
    * @author CuCuChen
    * @version $Id$
    * @since 2004-7-27
    */
    public class XmlFactory {

        public static Document readXMLFile(String inFile) throws XmlFactoryException {

            //为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = null;
            Document doc = null;

            try {
                db = dbf.newDocumentBuilder();
                doc = db.parse(inFile);

            } catch (DOMException dom) {
                System.out.println("--解析DOM出错-----\n");
                System.err.println(dom.getMessage());
                System.exit(1);
            } catch (IOException ioe) {
                System.out.println("--输入文件出错-----\n");
                System.err.println(ioe.getMessage());
                System.exit(1);
            } catch (ParserConfigurationException pce) {
                System.out.println("--解析配置出错-----\n");
                System.err.println(pce.getMessage());
                System.exit(1);
            } catch (Exception e) {
                System.err.println(e.getMessage());
                throw new XmlFactoryException(e.getMessage());

            }
            return doc;
        }


        public static Document readXMLFile() throws XmlFactoryException {

            //为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = null;
            Document doc = null;

            try {
                db = dbf.newDocumentBuilder();
                doc = db.newDocument();

            } catch (DOMException dom) {
                System.out.println("--解析DOM出错-----\n");
                System.err.println(dom.getMessage());
                System.exit(1);
            } catch (ParserConfigurationException pce) {
                System.out.println("--解析配置出错-----\n");
                System.err.println(pce.getMessage());
                System.exit(1);
            } catch (Exception e) {
                System.err.println(e.getMessage());
                throw new XmlFactoryException(e.getMessage());

            }
            return doc;
        }

        public static void transXMLFile(Document doc, String outFile) throws XmlFactoryException {

            DOMSource doms = new DOMSource(doc);
            //Input. Document is an extended class of Node, and therefore
            //can be used here.
            File f = new File(outFile);
            StreamResult sr = new StreamResult(f);
            // Output.
            try {
                TransformerFactory tf = TransformerFactory.newInstance();
                // Get a TransformerFactory.
                Transformer t = tf.newTransformer();
                // Make a new Transformer from it
                Properties properties = t.getOutputProperties();
                properties.setProperty(OutputKeys.ENCODING, "GB2312");
                properties.setProperty(OutputKeys.METHOD, "xml");
                properties.setProperty(OutputKeys.VERSION, "4.0");
                properties.setProperty(OutputKeys.INDENT, "yes");
                t.setOutputProperties(properties);
                // now proceed with the transformation
                t.transform(doms, sr);
                // Use the DOMSource as input. StreamResult as output path.
            } catch (TransformerConfigurationException tce) {
                System.out.println("Transformer Configuration Exception\n-----");
                tce.printStackTrace();
            } catch (TransformerException te) {
                System.out.println("Transformer Exception\n---------");
                te.printStackTrace();
            } catch (Exception e) {
                System.err.println(e.getMessage());
                throw new XmlFactoryException(e.getMessage());

            }

        }
    }


    //XmlFactoryException.java文件
    package com.cucu.xml.db;

    /**
    * @author CuCuChen
    * @version $Id$
    * @since 2004-7-27
    */
    public class XmlFactoryException extends Exception {
        public XmlFactoryException() {
            super();
        }

        public XmlFactoryException(String msg) {
            super(msg);
        }
    }


    //GbookBean.java文件
    package com.cucu.xml.gb;

    /**
    * @author CuCuChen
    * @version $Id$
    * @since 2004-7-28
    */
    public class GbookBean {

        String id;
        String url;
        String ip;
        String email;
        String qq;
        String time;
        String content;
        String name;
        String photo;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getIp() {
            return ip;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getQq() {
            return qq;
        }

        public void setQq(String qq) {
            this.qq = qq;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPhoto() {
            return photo;
        }

        public void setPhoto(String photo) {
            this.photo = photo;
        }

    }


    //对XML进行增删查改操作的核心程序代码GbookManager.java
    package com.cucu.xml.gb;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Text;
    import com.cucu.xml.db.XmlFactory;
    import com.cucu.xml.db.XmlFactoryException;

    import java.util.Vector;

    /**
    * @author CuCuChen
    * @version $Id$
    * @since 2004-7-27
    */


    /**
    * 操作XML数据库的基本方法
    * 1.查找全合记录集合
    * 2.根据ID查找相应记录
    * 3.增加一条记录
    * 4.修改一条记录
    * 5.删除一条记录
    */
    public class GbookManager {


        private static GbookManager ourInstance = new GbookManager();

        public static GbookManager getInstance() {
            return ourInstance;
        }

        Document doc = null;

        String inFile = null;
        String outFile = null;

        NodeList nodedata = null;
        NodeList nodeuser = null;

        Element root = null;
        Element data = null;
        Element user_id = null;

        public GbookManager() {
            inFile = "D:\\tomcat5.0\\webapps\\cms\\xml\\guestbook.xml";
            outFile = "D:\\tomcat5.0\\webapps\\cms\\xml\\guestbook.xml";
            try {
                //初始化文档工厂
                doc = XmlFactory.readXMLFile(inFile);
            } catch (XmlFactoryException e) {
                System.out.println("---------读取文档出错-----------");
                System.out.println(e.toString());
                System.out.println("-------------------------------");
            }
            //得到根节点
            root = doc.getDocumentElement();
        }

        /**
         * 返回留言记录集合
         *
         * @return Vector对象集合
         * @throws XmlFactoryException
         */
        public Vector Gbooks() throws XmlFactoryException {

            Vector vector = new Vector();

            //得到用户节点集合
            nodeuser = root.getElementsByTagName("user");
            for (int i = 0; i < nodeuser.getLength(); i++) {
                //依次取得用户元素
                user_id = (Element) nodeuser.item(i);

                GbookBean gbookbean = new GbookBean();

                //取得ID属性值
                String id = user_id.getAttribute("id");
                gbookbean.setId(id);

                //取得URL元素
                Element newurl = (Element) user_id.getElementsByTagName("url").item(0);
                //得到URL元素的子节点(其实就是文本)
                Node url_text = newurl.getFirstChild();
                gbookbean.setUrl(url_text.getNodeValue());

                Element newip = (Element) user_id.getElementsByTagName("ip").item(0);
                Node ip_text = newip.getFirstChild();
                gbookbean.setIp(ip_text.getNodeValue());

                Element newtime = (Element) user_id.getElementsByTagName("time").item(0);
                Node time_text = newtime.getFirstChild();
                gbookbean.setTime(time_text.getNodeValue());


                Element newqq = (Element) user_id.getElementsByTagName("qq").item(0);
                Node qq_text = newqq.getFirstChild();
                gbookbean.setQq(qq_text.getNodeValue());


                Element newemail = (Element) user_id.getElementsByTagName("email").item(0);
                Node email_text = newemail.getFirstChild();
                gbookbean.setEmail(email_text.getNodeValue());

                Element newename = (Element) user_id.getElementsByTagName("name").item(0);
                Node name_text = newename.getFirstChild();
                gbookbean.setName(name_text.getNodeValue());

                Element newephoto = (Element) user_id.getElementsByTagName("photo").item(0);
                Node photo_text = newephoto.getFirstChild();
                gbookbean.setPhoto(photo_text.getNodeValue());


                Element newcontent = (Element) user_id.getElementsByTagName("content").item(0);
                Node content_text = newcontent.getFirstChild();
                gbookbean.setContent(content_text.getNodeValue());

                vector.add(gbookbean);
            }

            return vector;
        }

        /**
         * 根据用户ID返回相应记录
         *
         * @param id 用户ID
         * @return 用户相应记录
         * @throws XmlFactoryException
         */
        public GbookBean Gbook(String id) throws XmlFactoryException {

            GbookBean gbookbean = new GbookBean();

            //得到用户节点集合
            nodeuser = root.getElementsByTagName("user");

            //根据ID找到相对应的的user元素
            for (int i = 0; i < nodeuser.getLength(); i++) {

                if ((((Element) nodeuser.item(i)).getAttribute("id")).equals(id)) {
                    user_id = (Element) nodeuser.item(i);
                    break;
                }

            }


            gbookbean.setId(id);
            //取得URL元素
            Element newurl = (Element) user_id.getElementsByTagName("url").item(0);
            //得到URL元素的子节点(其实就是文本)
            Node url_text = newurl.getFirstChild();
            gbookbean.setUrl(url_text.getNodeValue());

            Element newip = (Element) user_id.getElementsByTagName("ip").item(0);
            Node ip_text = newip.getFirstChild();
            gbookbean.setIp(ip_text.getNodeValue());


            Element newtime = (Element) user_id.getElementsByTagName("time").item(0);
            Node time_text = newtime.getFirstChild();
            gbookbean.setTime(time_text.getNodeValue());

            Element newqq = (Element) user_id.getElementsByTagName("qq").item(0);
            Node qq_text = newqq.getFirstChild();
            gbookbean.setQq(qq_text.getNodeValue());


            Element newemail = (Element) user_id.getElementsByTagName("email").item(0);
            Node email_text = newemail.getFirstChild();
            gbookbean.setEmail(email_text.getNodeValue());

            Element newename = (Element) user_id.getElementsByTagName("name").item(0);
            Node name_text = newename.getFirstChild();
            gbookbean.setName(name_text.getNodeValue());


            Element newephoto = (Element) user_id.getElementsByTagName("photo").item(0);
            Node photo_text = newephoto.getFirstChild();
            gbookbean.setPhoto(photo_text.getNodeValue());


            Element newcontent = (Element) user_id.getElementsByTagName("content").item(0);
            Node content_text = newcontent.getFirstChild();
            gbookbean.setContent(content_text.getNodeValue());

            return gbookbean;
        }

        /**
         * 增加一个用户信息
         *
         * @param url
         * @param ip
         * @param time
         * @param qq
         * @param email
         * @param name
         * @param photo
         * @param content
         * @throws XmlFactoryException
         */
        public void addGbook(String url, String ip,
                             String time, String qq,
                             String email, String name,
                             String photo, String content) throws XmlFactoryException {

            int datanum = 1;

            //得到名为data的节点集合
            nodedata = root.getElementsByTagName("data");

            //得到名为user的节点集合
            nodeuser = root.getElementsByTagName("user");

            //得到data 结点的第一个元素
            data = (Element) nodedata.item(0);
            int max_user_index = nodeuser.getLength() - 1;

            if (max_user_index > -1) {

                Element max_user = (Element) nodeuser.item(max_user_index);
                String max_user_id = max_user.getAttribute("id");
                datanum = Integer.parseInt(max_user_id) + 1;
            }


            //先创建一个元素
            Element user = doc.createElement("user");
            //设置元素属性
            user.setAttribute("id", String.valueOf(datanum));
            //在data元素里追加user元素
            data.appendChild(user);

            Element newurl = doc.createElement("url");

            //在user元素里追加url元素
            user.appendChild(newurl);
            //设置url元素的文本
            Text tURL = doc.createTextNode(url);
            //在url元素里追加文本
            newurl.appendChild(tURL);

            Element newip = doc.createElement("ip");
            user.appendChild(newip);
            Text tIP = doc.createTextNode(ip);
            newip.appendChild(tIP);

            Element newtime = doc.createElement("time");
            user.appendChild(newtime);
            Text tTIME = doc.createTextNode(time);
            newtime.appendChild(tTIME);

            Element newqq = doc.createElement("qq");
            user.appendChild(newqq);
            Text tQQ = doc.createTextNode(qq);
            newqq.appendChild(tQQ);

            Element newemail = doc.createElement("email");
            user.appendChild(newemail);
            Text tEMAIL = doc.createTextNode(email);
            newemail.appendChild(tEMAIL);

            Element newname = doc.createElement("name");
            user.appendChild(newname);
            Text tNAME = doc.createTextNode(name);
            newname.appendChild(tNAME);

            Element newphoto = doc.createElement("photo");
            user.appendChild(newphoto);
            Text tPHOTO = doc.createTextNode(photo);
            newphoto.appendChild(tPHOTO);

            Element newcontent = doc.createElement("content");
            user.appendChild(newcontent);
            Text tCONTENT = doc.createTextNode(content);
            newcontent.appendChild(tCONTENT);

            //文本传换,生成新的XML文档
            XmlFactory.transXMLFile(doc, outFile);
        }

        /**
         * 修改一个用户信息
         *
         * @param id
         * @param url
         * @param ip
         * @param time
         * @param qq
         * @param email
         * @param name
         * @param photo
         * @param content
         * @throws XmlFactoryException
         */
        public void updateGbook(String id,
                                String url, String ip,
                                String time, String qq,
                                String email, String name,
                                String photo, String content) throws XmlFactoryException {

            //得到用户节点集合
            nodeuser = root.getElementsByTagName("user");

            //根据ID找到相对应的要修改的user元素
            for (int i = 0; i < nodeuser.getLength(); i++) {

                if ((((Element) nodeuser.item(i)).getAttribute("id")).equals(id)) {
                    user_id = (Element) nodeuser.item(i);
                    break;
                }

            }

            //取得URL元素
            Element newurl = (Element) user_id.getElementsByTagName("url").item(0);
            //得到URL元素的子节点(其实就是文本)
            Node url_text = newurl.getFirstChild();
            //创建一个新的节点
            Text tURL = doc.createTextNode(url);
            //将URL元素的子节点替换掉(也就是替换文本)
            //注意:节点有可能是纯文本,也有可能是子节点
            newurl.replaceChild(tURL, url_text);

            Element newip = (Element) user_id.getElementsByTagName("ip").item(0);
            Node ip_text = newip.getFirstChild();
            Text tIP = doc.createTextNode(ip);
            newip.replaceChild(tIP, ip_text);


            Element newtime = (Element) user_id.getElementsByTagName("time").item(0);
            Node time_text = newtime.getFirstChild();
            Text tTIME = doc.createTextNode(time);
            newtime.replaceChild(tTIME, time_text);


            Element newqq = (Element) user_id.getElementsByTagName("qq").item(0);
            Node qq_text = newqq.getFirstChild();
            Text tQQ = doc.createTextNode(qq);
            newqq.replaceChild(tQQ, qq_text);


            Element newemail = (Element) user_id.getElementsByTagName("email").item(0);
            Node email_text = newemail.getFirstChild();
            Text tEMAIL = doc.createTextNode(email);
            newemail.replaceChild(tEMAIL, email_text);

            Element newename = (Element) user_id.getElementsByTagName("name").item(0);
            Node name_text = newename.getFirstChild();
            Text tNAME = doc.createTextNode(name);
            newename.replaceChild(tNAME, name_text);


            Element newephoto = (Element) user_id.getElementsByTagName("photo").item(0);
            Node photo_text = newephoto.getFirstChild();
            Text tPHOTO = doc.createTextNode(photo);
            newephoto.replaceChild(tPHOTO, photo_text);


            Element newcontent = (Element) user_id.getElementsByTagName("content").item(0);
            Node content_text = newcontent.getFirstChild();
            Text tCONTENT = doc.createTextNode(content);
            newcontent.replaceChild(tCONTENT, content_text);


            //文本传换,生成新的XML文档
            XmlFactory.transXMLFile(doc, outFile);
        }

        /**
         * 删除一个用户信息
         *
         * @param id
         * @throws XmlFactoryException
         */

        public void removeGbook(String id) throws XmlFactoryException {

            //取得数据节点集合
            nodedata = root.getElementsByTagName("data");
            //得到用户节点集合
            nodeuser = root.getElementsByTagName("user");

            //根据ID找到相对应的要删除的user元素
            for (int i = 0; i < nodeuser.getLength(); i++) {

                if ((((Element) nodeuser.item(i)).getAttribute("id")).equals(id)) {
                    user_id = (Element) nodeuser.item(i);
                    break;
                }

            }

           //根据用户ID删除一个用户基本信息
            nodedata.item(0).removeChild(user_id);

           //文本传换,生成新的XML文档
            XmlFactory.transXMLFile(doc, outFile);
        }

        /**
         * 调用一个实例
         *
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception {
            GbookManager gm = GbookManager.getInstance();
            try {

    //            gm.addGbook("http://www.linewell.com", "192.168.1.110",
    //                    "2004-07-28", "888888",
    //                    "webmaster@linewell.com", "xiechuanhai",
    //                    "linewell.jpg", "测试一下修改呵");
    //            gm.updateGbook("8", "http://alas520.126.com", "192.168.1.223",
    //                    "2004-07-28", "43767528",
    //                    "xch@linewell.com", "xiechuanhai",
    //                    "test.jpg", "小谢测试一下修改呵");
                 gm.removeGbook("8");

    //            Vector vc = gm.Gbooks();
    //            for (int i = 0; i < vc.size(); i++) {
    //                GbookBean gb = (GbookBean) vc.get(i);
    //                System.out.println("第" + (i + 1) + "条开始:");
    //                System.out.println(gb.getId());
    //                System.out.println(gb.getIp());
    //                System.out.println(gb.getUrl());
    //                System.out.println(gb.getTime());
    //                System.out.println(gb.getQq());
    //                System.out.println(gb.getEmail());
    //                System.out.println(gb.getName());
    //                System.out.println(gb.getPhoto());
    //                System.out.println(gb.getContent());
    //                System.out.println("第" + (i + 1) + "条结束。");
    //            }

    //            GbookBean gb = gm.Gbook("1");
    //
    //            System.out.println(gb.getId());
    //            System.out.println(gb.getIp());
    //            System.out.println(gb.getUrl());
    //            System.out.println(gb.getTime());
    //            System.out.println(gb.getQq());
    //            System.out.println(gb.getEmail());
    //            System.out.println(gb.getName());
    //            System.out.println(gb.getPhoto());
    //            System.out.println(gb.getContent());


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //这是小弟我花了两天写成的一个小东西,几乎包括了对DOM的所有操作,希望能对大家有所帮助,此程序编译后完全可以通过(注:alas520也就是cucuchen)我用一个帐号发不完贴,,,如果有什么问题希望能与我交流.E-mail:cucuchen520@163.com


       收藏   分享  
    顶(0)
      




    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2004/7/31 22:37:00
     
     绝情酷哥 帅哥哟,离线,有人找我吗?
      
      
      等级:大一(高数修炼中)
      文章:2
      积分:121
      门派:XML.ORG.CN
      注册:2004/7/31

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给绝情酷哥发送一个短消息 把绝情酷哥加入好友 查看绝情酷哥的个人资料 搜索绝情酷哥在『 DOM/SAX/XPath 』的所有贴子 引用回复这个贴子 回复这个贴子 查看绝情酷哥的博客2
    发贴心情 
    //小弟马子让别人给拐跑了,伤心欲绝之下又用SAX写得对以上XML留言本的查询操作,以示愤怒
    //SaxFactory.java
    package com.cucu.xml.db;

    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;
    import com.cucu.xml.gb.GbookReader;

    /**
    * @author CuCuChen
    * @version $Id$
    * @since 2004-7-31
    */
    public class SaxFactory {

        boolean validation = false;
        SAXParser saxParser = null;

        public SaxFactory() {

            //初始化SAX工厂
            SAXParserFactory spf = SAXParserFactory.newInstance();
            //不对XML进行验证
            spf.setValidating(validation);

            try {
                //新建一个解析器
                saxParser = spf.newSAXParser();
            } catch (Exception ex) {
                System.err.println(ex);
                System.exit(1);
            }
        }

        /**
         * @param fileName 要进行解析的XML文档
         * @param gr       具体的解析实现类
         */
        public  void parseXMLDocument(String fileName, GbookReader gr) {
            try {
                //解析XML
                saxParser.parse(new File(fileName), gr);
            } catch (SAXException se) {
                System.err.println(se.getMessage());
                System.exit(1);
            } catch (IOException ioe) {
                System.err.println(ioe);
                System.exit(1);
            }
        }
    }


    //SaxFactoryException.java
    package com.cucu.xml.db;

    /**
    * @author CuCuChen
    * @version $Id$
    * @since 2004-7-31
    */
    public class SaxFactoryException extends Exception {
        public SaxFactoryException() {
            super();
        }

        public SaxFactoryException(String msg) {
            super(msg);
        }
    }


    //GbookReader.java
    package com.cucu.xml.gb;

    import com.cucu.xml.db.SaxFactory;
    import com.cucu.xml.db.SaxFactoryException;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;

    import java.util.*;

    /**
    * @author CuCuChen
    * @version $Id$
    * @since 2004-7-31
    */
    public class GbookReader extends DefaultHandler {
        Stack tags = null;
        Hashtable hashtable = null;
        String id, url, ip, time, qq, email, name, photo, content;

        /**
         * 开始读取XML文档初始化的方法
         *
         * @throws SAXException
         */
        public void startDocument() throws SAXException {

            System.out.println("------Parse Begin--------");
            tags = new Stack();
            hashtable = new Hashtable();
        }

        /**
         * 结束读取XML文档的方法
         *
         * @throws SAXException
         */
        public void endDocument() throws SAXException {
            System.out.println("------Parse End--------");
        }

        /**
         * 开始一个元素的方法
         *
         * @param p0
         * @param p1
         * @param p2
         * @param p3
         * @throws SAXException
         */
        public void startElement(String p0, String p1, String p2, Attributes p3) throws SAXException {

            System.out.println("SAX Event: START qName[ " + p2 + " ]");
            if (p2.equals("user") && (p3.getQName(0).equals("id"))) {

                // 取得用户元素的ID属性值
                id = p3.getValue(0);

            }
            tags.push(p2);
        }

        /**
         * 结束一个元素的方法
         *
         * @param p0
         * @param p1
         * @param p2
         * @throws SAXException
         */
        public void endElement(String p0, String p1, String p2) throws SAXException {

            System.out.println("SAX Event: END qName[ " + p2 + " ]");
            tags.pop();
            if (p2.equals("user")) {
                addToContainer();
            }
        }

        /**
         * 开始一段文本的方法
         *
         * @param p0
         * @param p1
         * @param p2
         * @throws SAXException
         */
        public void characters(char[] p0, int p1, int p2) throws SAXException {
            //从栈中得到当前节点的信息
            String tag = (String) tags.peek();
            String str = new String(p0, p1, p2);
            if (tag.equals("url")) {
                url = str;
            } else if (tag.equals("ip")) {
                ip = str;
            } else if (tag.equals("time")) {
                time = str;
            } else if (tag.equals("qq")) {

            } else if (tag.equals("email")) {
                email = str;
            } else if (tag.equals("name")) {
                name = str;
            } else if (tag.equals("photo")) {
                photo = str;
            } else if (tag.equals("content")) {
                content = str;
            }
        }

        /**
         * 将数据增加到容器里
         */
        public void addToContainer() {
            GbookBean gb = new GbookBean();
            gb.setId(id);
            gb.setUrl(url);
            gb.setIp(ip);
            gb.setTime(time);
            gb.setQq(qq);
            gb.setEmail(email);
            gb.setName(name);
            gb.setPhoto(photo);
            gb.setContent(content);
            hashtable.put("user_" + id, gb);
        }

        /**
         * 返回用户信息记录集合
         *
         * @return Iterator 用户信息记录集合
         */
        public Iterator getGbooks() {
            return hashtable.values().iterator();
        }

        /**
         * 根据用户ID返回一个GbookBean对象
         *
         * @param id 用户ID
         * @return GbookBean
         */
        public GbookBean getGbook(String id) {
            return (GbookBean) hashtable.get("user_" + id);
        }

        public static void main(String[] args) throws SaxFactoryException {
            String fileName = "D:\\tomcat5.0\\webapps\\cms\\xml\\guestbook.xml";
            SaxFactory sf = new SaxFactory();
            GbookReader gr = new GbookReader();
            try {

                sf.parseXMLDocument(fileName, gr);

                Iterator it = gr.getGbooks();
                while (it.hasNext()) {
                    GbookBean gb = (GbookBean) it.next();
                    System.out.println(gb.getContent());
                }

                //GbookBean gb = gr.getGbook("1");
                //System.out.println(gb.getContent());
            } catch (Exception e) {
                throw new SaxFactoryException(e.toString());
            }
        }
    }

    在此本人不想对dom和sax编程之间的区别再作过多的说明,我好饿啊,先吃完饭吧
    If you wanna contact with me
    My QQ:43763062
    My MSN:f4_520cn@hotmail.com
    My E-mail:cucuchen520@163.com
    Thank you for your reading......

    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2004/7/31 22:40:00
     
     yuji1998 帅哥哟,离线,有人找我吗?魔羯座1981-12-22
      
      
      威望:5
      头衔:蓝色先锋
      等级:大二(研究C++)
      文章:212
      积分:1059
      门派:XML.ORG.CN
      注册:2004/4/10

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给yuji1998发送一个短消息 把yuji1998加入好友 查看yuji1998的个人资料 搜索yuji1998在『 DOM/SAX/XPath 』的所有贴子 访问yuji1998的主页 引用回复这个贴子 回复这个贴子 查看yuji1998的博客3
    发贴心情 
    很好,奖励一下

    ----------------------------------------------
    私人网站:蓝尚WEB商务平台http://www.lanshang.com     建站黄页:http://www.lanshang.com/link.asp WEB技术文库:http://www.lanshang.com/wenzhang/ 
    电子书籍: http://www.lanshang.com/ebook/  技术交流:http://www.lanshang.com/bbs/

    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2004/8/2 16:54:00
     
     GoogleAdSense魔羯座1981-12-22
      
      
      等级:大一新生
      文章:1
      积分:50
      门派:无门无派
      院校:未填写
      注册:2007-01-01
    给Google AdSense发送一个短消息 把Google AdSense加入好友 查看Google AdSense的个人资料 搜索Google AdSense在『 DOM/SAX/XPath 』的所有贴子 访问Google AdSense的主页 引用回复这个贴子 回复这个贴子 查看Google AdSense的博客广告
    2024/5/19 22:30:48

    本主题贴数3,分页: [1]

    管理选项修改tag | 锁定 | 解锁 | 提升 | 删除 | 移动 | 固顶 | 总固顶 | 奖励 | 惩罚 | 发布公告
    W3C Contributing Supporter! W 3 C h i n a ( since 2003 ) 旗 下 站 点
    苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
    218.750ms