SAX解析XML

SAX是事件驱动的,文档的读入过程就是SAX的解析过程。

在读入的过程中,遇到不同的项目,解析器会调用不同的处理方法。

1.对下面xml文档解析:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <bookstore>
 4     <book category="children">
 5           <title lang="en">Harry Potter</title> 
 6           <author>J K. Rowling</author> 
 7           <year>2005</year> 
 8           <price>29.99</price> 
 9     </book>
10 
11     <book category="cooking">
12           <title lang="en">Everyday Italian</title> 
13           <author>Giada De Laurentiis</author> 
14           <year>2005</year> 
15           <price>30.00</price> 
16     </book>
17 
18     <book category="web">
19           <title lang="en">Learning XML</title> 
20           <author>Erik T. Ray</author> 
21           <year>2003</year> 
22           <price>39.95</price> 
23     </book>
24 
25     <book category="web">
26           <title lang="en">XQuery Kick Start</title> 
27           <author>James McGovern</author> 
28           <author>Per Bothner</author> 
29           <author>Kurt Cagle</author> 
30           <author>James Linn</author> 
31          <author>Vaidyanathan Nagarajan</author> 
32           <year>2003</year> 
33           <price>49.99</price> 
34     </book>
35 
36 </bookstore>

注意:将book.xml文档放到目录,相同的位置。

 

 

先来看一个简单的例子:

 1 package com.sax.test;
 2 
 3 import java.io.File;
 4 
 5 import javax.xml.parsers.ParserConfigurationException;
 6 import javax.xml.parsers.SAXParser;
 7 import javax.xml.parsers.SAXParserFactory;
 8 
 9 import org.xml.sax.Attributes;
10 import org.xml.sax.SAXException;
11 import org.xml.sax.helpers.DefaultHandler;
12 
13 public class SaxTest1 {
14 
15     /**
16      * @param args
17      * @throws Exception 
18      *
19      */
20     public static void main(String[] args) throws Exception {
21         // TODO Auto-generated method stub
22 
23         // 第一步建立sax解析工厂
24         SAXParserFactory  spf = SAXParserFactory.newInstance();
25         //第二步建立sax解析器
26         SAXParser sp = spf.newSAXParser();
27         //第三步开始进行解析
28         sp.parse(new File("book.xml"), new MyHandler());
29 
30     }
31 
32 }
33 class MyHandler extends DefaultHandler
34 {
35     @Override
36     public void startDocument() throws SAXException {
37         
38         System.out.println("start doc");
39     }
40     @Override
41     public void endDocument() throws SAXException {
42         System.out.println("end doc");
43     }
44     @Override
45     public void startElement(String uri, String localName, String qName,
46             Attributes attributes) throws SAXException {
47         System.out.println("start element");
48     }
49     @Override
50     public void endElement(String uri, String localName, String qName)
51             throws SAXException {
52         System.out.println("end element");
53     }
54 }

结果为:

start doc
start element
start element
start element
end element
start element
end element
start element
end element
start element
end element
end element
start element
start element
end element
start element
end element
start element
end element
start element
end element
end element
start element
start element
end element
start element
end element
start element
end element
start element
end element
end element
start element
start element
end element
start element
end element
start element
end element
start element
end element
start element
end element
start element
end element
start element
end element
start element
end element
end element
end element
end doc

示例二:

package com.sax.test;

import java.io.File;
import java.util.Stack;

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 SaxTest2 {

    /**
     * @param args
     * @throws Exception 
     * 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        
        SAXParserFactory factory = SAXParserFactory.newInstance();
        
        SAXParser parser = factory.newSAXParser();
        
        parser.parse(new File("book.xml"), new MyHandler2());
        
    }

}

class MyHandler2 extends DefaultHandler
{
    //保存之前出现的标签
    private Stack<String> stack = new Stack<String>();
    
    private String title;
    
    private String author;
    
    private String year;
    
    private String price;
    
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        stack.push(qName);
        
        for(int i=0; i<attributes.getLength(); i++)   //元素的所有属性
        {
            String attrName = attributes.getQName(i);
            String attrValue  =attributes.getValue(i);
            System.out.println(attrName+", "+attrValue);
            
        }
    }
    
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        String tag = stack.peek();    //去除元素
        if("title".equals(tag))
        {
            title = new String(ch,start,length);
        }else if("author".equals(tag))
        {
            author = new String(ch,start,length);
        }else if("year".equals(tag))
        {
            year = new String(ch, start, length);
        }else if("price".equals(tag))
        {
            price = new String(ch, start, length);
        }
    }
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
       stack.pop(); //表示该元素已经用完。
       
       if("book".equals(qName))   
       {
           System.out.println("title "+title);
           System.out.println("author "+author);
           System.out.println("year "+year);
           System.out.println("price "+price);
       }
    }
        
}

运行结果为:

--------圣思圆xml视频

 

posted @ 2014-08-11 21:07  lzyer  阅读(297)  评论(0)    收藏  举报