SAX解析XML文件示例

前端之家收集整理的这篇文章主要介绍了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

猜你在找的XML相关文章