zoukankan      html  css  js  c++  java
  • event based xml parser (SAX) demo

    import java.io.ByteArrayInputStream;
    
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    public class Test {
        public static void main(String[] args) throws Exception {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            String s = "<班级 id="1"><教师 id="2">王老师</教师><学生 id="3">小明</学生></班级>";
            ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes("utf-8"));
            SaxHandler handler = new SaxHandler();
            parser.parse(is, handler);
        }
    }
    
    class SaxHandler extends DefaultHandler {
        @Override
        public void startDocument() throws SAXException {
            System.out.println("start document");
        }
    
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            System.out.println(uri + "|" + localName + "|" + qName + "|" + attributes.getValue(0));
        }
    
        @Override
        public void characters(char ch[], int start, int length) throws SAXException {
            System.out.println(new String(ch, start, length));
        }
    
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            System.out.println(uri + "!" + localName + "!" + qName);
        }
    
        @Override
        public void endDocument() throws SAXException {
            System.out.println("end document");
        }
    }

    运行结果:

    start document
    ||班级|1
    ||教师|2
    王老师
    !!教师
    ||学生|3
    小明
    !!学生
    !!班级
    end document
  • 相关阅读:
    奋斗了一晚上,搞定了Ant
    我很成功,我很失败
    管理复杂性
    Rapid framework(SSH)数据流概述
    Strtus2 Convention Plugin学习(转)
    16X16 经典silk图标 (famfamfam.com)
    v512 Oracle数据库实用教程 演示用ppt(转pdf)
    RapidFramework使用Oracle的步骤
    oracle 找出最耗资源的sql (dolphin_ygj)
    jquery validate 中文化
  • 原文地址:https://www.cnblogs.com/zno2/p/6709545.html
Copyright © 2011-2022 走看看