本文简单介绍通过SAX方式生成xml文件的方法。
例子:解析下面的xml文件并生成新的具有同样结构的xml文件
book.xml
<bookstore>
<book id="1">
<name>冰与火之歌name>
<author>乔治马丁author>
<year>2014year>
<price>89price>
book>
<book id="2">
<name>安徒生童话name>
<year>2004year>
<price>77price>
<language>Englishlanguage>
book>
bookstore>
实现代码:
book类:
package com.imooc.entity;
public class Book {
private String id;
private String name;
private String author;
private String year;
private String price;
private String language;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
SAXParserHandler类:
package com.imooc.Handler;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.imooc.entity.Book;
public class SAXParserHandler extends DefaultHandler {
int bookIndex=0;
String value=null;
Book book=null;
private ArrayList bookList=new ArrayList();
public ArrayList getBookList() {
return bookList;
}
/**
* 用来遍历xml的开始标签
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
if(qName.equals("book")){
book=new Book();
bookIndex++;
System.out.println("================开始遍历第"+bookIndex+"本书内容================");
// //已知book下属性的名称及个数,根据属性名得到属性值
// String value=attributes.getValue("id");
// System.out.println("book的属性值是"+value);
//若不知道book下属性的名称和个数
int num=attributes.getLength();
for(int i=0;i"book元素的第"+(i+1)+"个属性名:"
+attributes.getQName(i));
System.out.println("--属性值为:"+attributes.getValue(i));
if(attributes.getQName(i).equals("id")){
book.setId(attributes.getValue(i));
}
}
}
else if(!qName.equals("bookstore")){
System.out.print("结点名是:"+qName);
}
}
/**
* 用来遍历xml的结束标签
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
//判断是否针对一本书已经遍历结束
if(qName.equals("book")){
bookList.add(book);
book=null;
System.out.println("================结束遍历第"+bookIndex+"本书内容================");
}
else if(qName.equals("name")){
book.setName(value);
}
else if(qName.equals("author")){
book.setAuthor(value);
}
else if(qName.equals("year")){
book.setYear(value);
}
else if(qName.equals("price")){
book.setPrice(value);
}
else if(qName.equals("language")){
book.setLanguage(value);
}
}
/**
* 用来标识解析开始
*/
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
System.out.println("SAX解析开始");
}
/**
* 用来标识解析结束
*/
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
System.out.println("SAX解析结束");
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
value=new String(ch,start,length);
if(!value.trim().equals("")){
System.out.println("--结点值为:"+value);
}
}
}
SAXTest类:
package com.imooc.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import com.imooc.Handler.SAXParserHandler;
import com.imooc.entity.Book;
public class SAXTest {
public ArrayList parseXML() {
// 获取一个SAXParserFactory的实例
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParserHandler handler = null;
// 通过factory获取SAXParser实例
try {
SAXParser parser = factory.newSAXParser();
// 创建SAXParserHandler对象
handler = new SAXParserHandler();
parser.parse("book.xml", handler);
System.out
.println("~!~!~!共有" + handler.getBookList().size() + "本书");
for (Book book : handler.getBookList()) {
System.out.println(book.getId());
System.out.println(book.getName());
System.out.println(book.getAuthor());
System.out.println(book.getYear());
System.out.println(book.getPrice());
System.out.println(book.getLanguage());
System.out.println("-------finish-------");
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return handler.getBookList();
}
/**
* 生成xml
*
* @param args
*/
public void creatXML() {
ArrayList bookList = parseXML();
// 1.创建一个SAXTransformerFactory类的对象
SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();
try {
// 2.通过SAXTransformerFactory对象创建一个TransformerHandler对象
TransformerHandler handler = tff.newTransformerHandler();
// 3.通过handler对象创建一个Transformer对象
Transformer tf = handler.getTransformer();
// 4.通过Transformer对象对生成的xml文件进行设置
// 设置xml的编码
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// 设置xml是否换行
tf.setOutputProperty(OutputKeys.INDENT, "yes");
// 5.创建一个Result对象
File f = new File("newBook.xml");
if (!f.exists()) {
f.createNewFile();
}
// 6.是result和handler关联
Result result = new StreamResult(new FileOutputStream(f));
handler.setResult(result);
// 7.利用handler对象进行xml文件内容的编写
// 打开document
handler.startDocument();
AttributesImpl attr = new AttributesImpl();
handler.startElement("", "", "bookstore", attr);
for (Book book : bookList) {
//创建book节点
attr.clear();
attr.addAttribute("", "", "id", "", book.getId());
handler.startElement("", "", "book", attr);
//创建name节点
if(book.getName()!=null&&!book.getName().trim().equals("")){
attr.clear();
handler.startElement("", "", "name", attr);
handler.characters(book.getName().toCharArray(), 0, book
.getName().toCharArray().length);
handler.endElement("", "", "name");
}
//创建year节点
if(book.getYear()!=null&&!book.getYear().trim().equals("")){
handler.startElement("", "", "year", attr);
handler.characters(book.getYear().toCharArray(), 0, book
.getYear().toCharArray().length);
handler.endElement("", "", "year");
}
//创建author节点
if(book.getAuthor()!=null&&!book.getAuthor().trim().equals("")){
handler.startElement("", "", "author", attr);
handler.characters(book.getAuthor().toCharArray(), 0, book
.getAuthor().toCharArray().length);
handler.endElement("", "", "author");
}
//创建price节点
if(book.getPrice()!=null&&!book.getPrice().trim().equals("")){
handler.startElement("", "", "price", attr);
handler.characters(book.getPrice().toCharArray(), 0, book
.getPrice().toCharArray().length);
handler.endElement("", "", "price");
}
//创建language节点
if(book.getLanguage()!=null&&!book.getLanguage().trim().equals("")){
handler.startElement("", "", "language", attr);
handler.characters(book.getLanguage().toCharArray(), 0, book
.getLanguage().toCharArray().length);
handler.endElement("", "", "language");
}
handler.endElement("", "", "book");
}
handler.endElement("", "", "bookstore");
// 关闭document
handler.endDocument();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
SAXTest st = new SAXTest();
// st.parseXML();
st.creatXML();
}
}
注意:生成xml文件时,setResult()方法一定要写在startDocument()方法之前。