zoukankan      html  css  js  c++  java
  • 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;

           }

          

    }

  • 相关阅读:
    bzoj4950
    P1377发奖金
    环信SDK与Apple Watch的结合(1)
    环信SDK与Apple Watch的结合(2)
    【Objective-C】0-第一个OC的类
    【Objective-C】4-空指针和野指针
    【Objective-C】3 -self关键字
    【Objective-C】2.自定义构造方法和description方法
    Swift函数|闭包
    Swift枚举|结构体|类|属性|方法|下标脚本|继承
  • 原文地址:https://www.cnblogs.com/itfenqing/p/4429524.html
Copyright © 2011-2022 走看看