• SAX解析XML


    一、使用SAX解析xml文件

    新建一个类,继承之DefaultHandler:

    示例代码如下:

    package org.demo.saxxml;

    import org.xml.sax.Attributes;

    import org.xml.sax.SAXException;

    import org.xml.sax.helpers.DefaultHandler;

    public class MyContentsHandler extends DefaultHandler {

           String Name,Sex;

           String tagName;

           String xmlContent="";

           @Override

    //解析每个标签的时候调用的方法

           public void characters(char[] ch, int start, int length)

                         throws SAXException {

                  if(tagName.equals("Name")){

                         Name=new String(ch,start,length);

                         System.out.println(Name);

                  }else if(tagName.equals("Sex")){

                         Sex=new String(ch,start,length);

                  }

                  super.characters(ch, start, length);

           }

    //解析xml文档结束时

           @Override

           public void endDocument() throws SAXException {

                  // TODO Auto-generated method stub

                  System.out.println("End...");

                 

                  super.endDocument();

           }

    //解析xml标签结束时

           @Override

           public void endElement(String uri, String localName, String qName)

                         throws SAXException {

                  // TODO Auto-generated method stub

                  if(localName.equals("Name")){

                         xmlContent+=Name+"|";

                         System.out.println(xmlContent);

                  }else if(localName.equals("Sex")){

                         xmlContent+=Sex+"<br>";

                  }

                  super.endElement(uri, localName, qName);

           }

    //解析xml文档开始时

           @Override

           public void startDocument() throws SAXException {

                  // TODO Auto-generated method stub

                  super.startDocument();

           }

    //解析xml标签开始时

           @Override

           public void startElement(String uri, String localName, String qName,

                         Attributes attributes) throws SAXException {

                  // TODO Auto-generated method stub

                  tagName=localName;

                  super.startElement(uri, localName, qName, attributes);

           }

           public String getContent(){

                  return xmlContent;

           }

          

    }

  • 相关阅读:
    进程与线程的区别
    信号列表详解
    同步与互斥
    互斥锁
    读写锁
    Redis QPS测试
    从分布式锁来看redis和zookpeer!
    JVM虚拟机调参
    log4j.properties配置详解与实例
    生产者消费者(消费者要消费完才能退出)
  • 原文地址:https://www.cnblogs.com/itfenqing/p/4429524.html
Copyright © 2020-2023  润新知