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
*
* @author spirit_fly
* SAX解析XML文件
* 优点,简单
*
*/
public class SAXtoMyxml {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
// 通过工厂获得SAX解析器
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
//解析器
// 通过解析器解析xml文件
sax.parse("myxml1.xml", new SAXHander()); //使用自定义的监听器
}
}
// 自定义sax解析监听器
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文件中的空格节点
if(text.trim().equals("")) {
return;
}
System.out.println("文本内容 "+text);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("元素结束 "+qName);
}
public void endDocument() throws SAXException {
System.out.println("文档结束 ");
}
}
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
*
* @author spirit_fly
* SAX解析XML文件
* 优点,简单
*
*/
public class SAXtoMyxml {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
// 通过工厂获得SAX解析器
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
//解析器
// 通过解析器解析xml文件
sax.parse("myxml1.xml", new SAXHander()); //使用自定义的监听器
}
}
// 自定义sax解析监听器
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文件中的空格节点
if(text.trim().equals("")) {
return;
}
System.out.println("文本内容 "+text);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("元素结束 "+qName);
}
public void endDocument() throws SAXException {
System.out.println("文档结束 ");
}
}