SAX解析XML文件示例

package cn.com.songjy.test.xml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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

	public SAXDemo() throws FileNotFoundException,ParserConfigurationException,SAXException,IOException {
		printQuestions("product.xml");
	}

	public static void main(String[] args) {
		try {
			new SAXDemo();
		} catch (FileNotFoundException e) {
			e.printstacktrace();
		} catch (ParserConfigurationException e) {
			e.printstacktrace();
		} catch (SAXException e) {
			e.printstacktrace();
		} catch (IOException e) {
			e.printstacktrace();
		}
	}

	public void printQuestions(String xmlfile)
			throws ParserConfigurationException,FileNotFoundException,IOException {

		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();

		parser.parse(new FileInputStream(xmlfile),new DefaultHandler() {

			private boolean isQuestions = false;

			public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
				if (qName.equals("questions")) {
					isQuestions = true;
				}
			}

			public void characters(char[] ch,int start,int length)
					throws SAXException {
				if (isQuestions) {
					String str = new String(ch,start,length);

					System.out.println(str);

				}
			}

			public void endElement(String uri,String qName)
					throws SAXException {
				if (qName.equals("questions")) {
					isQuestions = false;
				}
			}

		});

	}
}


product.xml

<?xml version="1.0" encoding="UTF-8"?>
<product id="200">
	<name>UML Exam Simulator</name>
	<price>100</price>
	<topics name="UML">
		<topic id="UML_SM">
			<name>Static Modeling</name>
			<questions>100</questions>
		</topic>
		<topic id="UML_AE">
			<name>Architecture</name>
			<questions>80</questions>
		</topic>
		<topic id="UML_DM">
			<name>Dynamic Modeling</name>
			<questions>67</questions>
		</topic>
	</topics>
</product>


使用sax解析xml文件,并自动根据实体类class得到映射后的实体类list集合

SAX对底层操作的事例

JDOM对XML文档的读写增删改转换等

DOM4J对XML文档的读写增删改等

对XML文档操作的通用CRUD(JDOM版)

如何利用JDOM把XML文档全部解析出来

java XML -- SAX和StAX分析XML

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念