您的位置:首页 > 编程语言 > Java开发

Java 中使用 SAX 解析 XML 文档

2016-01-07 20:24 351 查看
本文档包含 5 个文件

分别为

1.Test.java

2.MainClass.java

3.Book.java

4.MySaxHandler.java

5.book.xml

代码见下图

PS:注释和结果已经很明显了 就不罗嗦了

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;

public class Test {

public static void main(String[] args) {
MainClass c = new MainClass();
ArrayList<Book> list = null;
try {
InputStream is = new FileInputStream("D:\\book.xml");
list = c.getSAXBooks(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < list.size(); i++) {
System.out.println("id:" + list.get(i).getId() + "name:"
+ list.get(i).getBookName()+" test:"
+ list.get(i).getTest()+" "+ "price:"
+ list.get(i).getBookPrice());
}
}
}

public class Book {
private String id;
private String bookName;
private float bookPrice;
private String test;

public String getId() {
return id;
}

public String getTest() {
return test;
}

public void setTest(String test) {
this.test = test;
}

public void setId(String id) {
this.id = id;
}

public String getBookName() {
return bookName;
}

public void setBookName(String bookName) {
this.bookName = bookName;
}

public float getBookPrice() {
return bookPrice;
}

public void setBookPrice(float bookPrice) {
this.bookPrice = bookPrice;
}

public Book(String id, String bookName, float bookPrice) {
super();
this.id = id;
this.bookName = bookName;
this.bookPrice = bookPrice;
}

public Book() {

}

}

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class MainClass {
public ArrayList<Book> getSAXBooks(InputStream is) {
SAXParserFactory factory = SAXParserFactory.newInstance();
//获得一个 SAXParser 对象
SAXParser parser = null;
try {
parser = factory.newSAXParser();
} catch (Exception e) {
e.printStackTrace();
}

MySaxHandler handler = new MySaxHandler();
try {
//调用 parse() 这个方法进行解析
parser.parse(is, handler);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return handler.getBookList();

}
}

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MySaxHandler extends DefaultHandler {
private ArrayList<Book> bookList;// 解析之后 XML 数据存储链表
private Book book = null;// 解析的节点对象(自定义的一个类)
private String tag = null;// 当前解析的元素标签

/**
* 接收元素中字符数据的通知 ch 字符数组 start 字符数组的起始程序 length 字符数组长度
*/

public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println("characters()");
if (null != tag && !"".equals(tag)) {// 避免空白
String value = new String(ch, start, length);
//测试
System.out.println("value is:" + value);
if ("name".equals(tag)) {
book.setBookName(value);
} else if ("price".equals(tag)) {
book.setBookPrice(Float.parseFloat(value));
} else if ("test".equals(tag)) {
book.setTest(value);
}
}
}

/**
* 文档解析结束
*
* @throws SAXException
*/
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("endDocument()-----></books>");
}

/**
* 接收文档的结尾的通知 uri:元素的命名空间 localName:元素的本地名称 name:元素的限定名
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("book")) {
bookList.add(book);
book = null;
}
if (qName.equals("bookTest")) {
bookList.add(book);
book = null;
}
System.out.println("endElement()-----> uri is:" + uri);
System.out.println("endElement()-----> localName is:" + localName);
System.out.println("endElement()-----> qName is:" + qName);

tag = null;
}

/**
* 文档解析开始
*/
public void startDocument() throws SAXException {
bookList = new ArrayList<Book>();
System.out.println("startDocument()-----><books>");
}

/**
* 接收元素开始 uri:元素的命名空间 localName:元素的本地名称 qName:元素的限定名(带前缀) atts:元素的属性集合
*/

public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.println("startElement()----->" + qName);

if ("book".equals(qName)) {
book = new Book();
String id = attributes.getValue("id");
book.setId(id);
}
if ("bookTest".equals(qName)) {
book = new Book();
String id = attributes.getValue("id");
book.setId(id);
}
tag = qName;
System.out.println("startElement() 中的 tag is: " + tag);
}

public ArrayList<Book> getBookList() {
System.out.println("ArrayList<Book>");
return bookList;
}
}

/////////////////////////////////////////////
XML 测试文档
/////////////////////////////////////////////
<?xml version="1.0" encoding="UTF-8"?>
<books>
<bookTest id = "1">
<name>thinking in java</name>
<test>test XML</test>
<price>85.5</price>
</bookTest>
<book id = "2">
<name>Spring in Action</name>
<price>39.0</price>
</book>
</books>

/////////////////////////////////////////////
小结
/////////////////////////////////////////////
*
* 调用 SAX 步骤
* 1.获得一个 SAXParser 对象
* 		SAXParserFactory factory = SAXParserFactory.newInstance();
* 		SAXParser parser = null;
* 2.从 SAXParserFactory 对象中获取一个 SAXParser 对象 这个对象调用 parse() 方法对 XML 进行解析
* 		parser.parse(is, handler);
* 3.构造一个 继承 DefaultHandler 的类 名为 MySaxHandler 实例化一个对象 handler 传入 parse(is,parse) 方法中
* 4.把 XML 文件建成一个对象 InputStream is = new FileInputStream("D:\\book.xml"); 传入 parse 方法中
*
*
*
* SAX 解析的物理步骤
* 1.详见运行结果
* */

/////////////////////////////////////////////
运行结果
/////////////////////////////////////////////、
startDocument()-----><books>
startElement()----->books
startElement() 中的 tag is: books
characters()
value is:

startElement()----->bookTest
startElement() 中的 tag is: bookTest
characters()
value is:

startElement()----->name
startElement() 中的 tag is: name
characters()
value is:thinking in java
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:name
characters()
startElement()----->test
startElement() 中的 tag is: test
characters()
value is:test XML
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:test
characters()
startElement()----->price
startElement() 中的 tag is: price
characters()
value is:85.5
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:price
characters()
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:bookTest
characters()
startElement()----->book
startElement() 中的 tag is: book
characters()
value is:

startElement()----->name
startElement() 中的 tag is: name
characters()
value is:Spring in Action
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:name
characters()
startElement()----->price
startElement() 中的 tag is: price
characters()
value is:39.0
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:price
characters()
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:book
characters()
endElement()-----> uri is:
endElement()-----> localName is:
endElement()-----> qName is:books
endDocument()-----></books>
ArrayList<Book>
id:1name:thinking in java test:test XML price:85.5
id:2name:Spring in Action test:null price:39.0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: