zoukankan      html  css  js  c++  java
  • SAX解析XML

    package ls.xml;
    
    import java.io.StreamCorruptedException;
    
    import javax.xml.stream.events.EndElement;
    import javax.xml.stream.events.StartElement;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    public class SAXParserHandler extends DefaultHandler {
        //遍历xml文件的开始标签
        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            if(qName.equals("book")){
                System.out.println("================开始遍历一本书===============");
                //System.out.println("book的属性值:"+attributes.getValue("id"));
                int num = attributes.getLength();
                for (int i = 0; i < num; i++) {
                    System.out.println("book的第"+(i+1)+"个属性"+attributes.getQName(i)+"--属性值:"+attributes.getValue(i));
                }
            }else if(!qName.equals("book")&&!qName.equals("bookstore")){
                 System.out.print("节点名是:"+qName);
            }
        }
        //遍历xml文件的结束标签
        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            super.endElement(uri, localName, qName);
            //判断一本书结束
            if(qName.equals("book")){
                System.out.println("================结束遍历一本书===============");
            }
        }
        //标志解析开始
        @Override
        public void startDocument() throws SAXException {
            super.startDocument();
            System.out.println("SAX解析开始");
        }
        //标志解析结束
        @Override
        public void endDocument() throws SAXException {
            super.endDocument();
            System.out.println("SAX解析结束");
        }
        //获取节点值,自动调用
        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            super.characters(ch, start, length);
            String value = new String(ch,start,length);
            if(!value.trim().equals(""))
                 System.out.println("--节点值是:"+value);    
        }
    }
    Jumping from failure to failure with undiminished enthusiasm is the big secret to success.
  • 相关阅读:
    15年双11手淘前端技术分享(转)
    高程第9章 客户端检测
    高程8.4 screen对象 8.5history对象 8.6小结
    高程8.2location对象 8.3navigator对象
    高程第8章 BOM 8.1window对象
    高程 7.3 模仿块级作用域 7.4私有变量 7.5小结
    高程 第7章函数表达式 7.1递归 7.2闭包
    23、GoAccess分析Nginx日志
    11、Nginx反向代理服务
    10、LNMP架构
  • 原文地址:https://www.cnblogs.com/chongerlishan/p/5944865.html
Copyright © 2011-2022 走看看