当前位置:编程学习 > XML/UML >>

JAVA SAX 方式解析XML文件

 

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");

}

}

 

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,