JAVA SAX 方式解析XML文件

2014-11-24 01:42:29 · 作者: · 浏览: 0

package com.czp;

import java.io.File;

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;

/***

* 的xml文件解析方式

* @author Caozp

* @version 1.0

*

*/

public class MySaxXml extends DefaultHandler {

@Override

public void endDocument() throws SAXException {

super.endDocument();

}

@Override

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

throws SAXException {

super.endElement(uri, localName, name);

}

/***

* 取XML的name and value

*可以将其只放到map中

* @param uri

* @param localName

* @param name

* @param attributes

* @throws SAXException

*/

@Override

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

Attributes attributes) throws SAXException {

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

if(attributes!=null){

for (int i = 0; i < attributes.getLength(); i++) {

System.out.println(attributes.getQName(i)+"\tvalue:"+attributes.getValue(i));

}

}

}

/***

* 实现解析

* @param xmlPath

* @throws Exception

*/

public void reader(String xmlPath) throws Exception{

SAXParserFactory factory = SAXParserFactory.newInstance();

SAXParser parser = factory.newSAXParser();

parser.parse(new File(xmlPath), new MySaxXml());

}

public static void main(String[] args) throws Exception {

new MySaxXml().reader("D:\\test.xml");

}

}