码迷,mamicode.com
首页 > 其他好文 > 详细

SAX解析XML文件实例代码

时间:2014-06-29 07:43:35      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   get   

bubuko.com,布布扣
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
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 XMLTest extends DefaultHandler {

    public void startDocument() throws SAXException{
        System.out.println("<?xml version=‘1.0‘ encoding=‘UTF-8‘ ?>");
    }
    public void processingInstruction(String target ,String data) throws SAXException{
        System.out.println("<?"+target+" "+data+"?>");
    }
    public void startElement(String uri,String localName,
            String qName,Attributes attrs)throws SAXException {
        System.out.print("<"+qName);
        int len=attrs.getLength();
        for(int i=0;i<len;i++){
            System.out.print(" ");
            System.out.print(attrs.getQName(i));
            System.out.print("=\"");
            System.out.print(attrs.getValue(i));
            System.out.print("\"");
        }
        System.out.print(">");
        List list=new ArrayList();
    }
    public void characters(char[] ch,int start,
            int length)throws SAXException {
        System.out.println(new String(ch,start,length));
    
    }
    public void endElement(String uri,String localName,
            String qName)throws SAXException {
        System.out.println("</"+qName+">");
    
    }
    public static void main(String[] args) {
        SAXParserFactory sdf=SAXParserFactory.newInstance();
        SAXParser sp=null;
        try {
            sp=sdf.newSAXParser();
            //aa.xml里面必须有数据,可以解析出来里面的内容
            File f=new File("c:/aa.xml");
            sp.parse(f,new XMLTest());
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
bubuko.com,布布扣

 

SAX解析XML文件实例代码,布布扣,bubuko.com

SAX解析XML文件实例代码

标签:style   blog   http   java   color   get   

原文地址:http://www.cnblogs.com/LT0314/p/3770046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!