JAVA技巧:sax解析xml文件操作代碼

字號(hào):

package com.yangrs;
    import java.io.IOException;
    import javax.xml.parsers.*;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    /**
    *
    * date 12008-12-16
    * SAX解析XML文件
    * 優(yōu)點(diǎn),簡(jiǎn)單
    *
    */
    public class SAXtoMyxml {
    public static void main(String[] args) throws ParserConfigurationException,
    SAXException, IOException {
    // 通過(guò)工廠獲得SAX解析器
    SAXParserFactory sf = SAXParserFactory.newInstance();
    SAXParser sax = sf.newSAXParser();
    //解析器
    // 通過(guò)解析器解析xml文件
    sax.parse("myxml1.xml", new SAXHander()); //使用自定義的監(jiān)聽器
    }
    }
    // 自定義sax解析監(jiān)聽器
    class SAXHander extends DefaultHandler {
    public void startDocument() throws SAXException {
    System.out.println("文檔開始 ");
    }
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    System.out.println("元素開始 "+qName);
    }
    public void characters(char[] ch, int start, int length) throws SAXException {
    String text = new String(ch,start,length);
    //去掉xml文件中的空格節(jié)點(diǎn)
    if(text.trim().equals("")) {
    return;
    }
    System.out.println("文本內(nèi)容 "+text);
    }
    public void endElement(String uri, String localName, String qName) throws SAXException {
    System.out.println("元素結(jié)束 "+qName);
    }
    public void endDocument() throws SAXException {
    System.out.println("文檔結(jié)束 ");
    }
    }