学习sax解析xml心得

可以使用SAXParser的parse方法进行解析,也可以使用XmlReader的parse方法进行解析,但是最好是使用XmlReader,因为XmlReader是接口。
基本的初始化方法如下:
File f=new File("d:"+File.separator+"e.xml");
        InputSource ip=new InputSource(new FileInputStream(f));
        try {
            SAXParser  s=SAXParserFactory.newInstance().newSAXParser();
            XMLReader xmlReader=s.getXMLReader();
            xmlReader.setContentHandler(new MyHandler());
            xmlReader.parse(ip);
            
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

其中MyHandler类继承了DefaultHandler,可以overwrite其中的方法,使其满足需求。
例子:

public void startElement(String uri, String localName, String name,
                Attributes attributes) throws SAXException {

            if (logger.isInfoEnabled()) {
                logger
                        .info("startElement(String, String, String, Attributes) - uri="
                                + uri
                                + ", localName="
                                + localName
                                + ", name="
                                + name );
            }

            for (int i = 0; i < attributes.getLength(); i++) {
                if (logger.isInfoEnabled()) {
                    logger.info("endElement(String, String, String) - uri=" + uri
                            + ", localName=" + localName + ", qName=" + attributes.getQName(i)+ ", attributes=" + attributes.getValue(i));
                }
            }
            

            super.startElement(uri, localName, name, attributes);
        }
//对text node的处理
public void characters(char[] ch, int start, int length)
                throws SAXException {
            if (logger.isInfoEnabled()) {
                logger.info("characters(char[], int, int) - ch="+ new String(ch,start,length));//这里这样子写才能得到text node 真正的值。范围: characters() 事件不仅包括不仅一个字符串。它还包括起始和长度信息。实际上,ch 字符数组包括整个文档。应用程序一定不能尝试读取馈送给 characters() 事件的范围之外的字符。
            }

            super.characters(ch, start, length);
        }


posted on 2007-11-15 17:27 刘铮 阅读(289) 评论(0)  编辑  收藏 所属分类: XML


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

留言簿(1)

文章分类(141)

文章档案(147)

搜索

最新评论