SAX方式生成XML文件

前端之家收集整理的这篇文章主要介绍了SAX方式生成XML文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package 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;
	}
	
	
}
package SAX.handler;

import java.util.ArrayList;

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

import entity.Book;


public class SAXParserHandler extends DefaultHandler {
	String value = null;
	Book book = null;
	private ArrayList<Book> bookList = new ArrayList<Book>();
	public ArrayList<Book> getBookList() {
		return bookList;
	}

	int bookIndex = 0;
	/**
	 * 用来标识解析开始
	 */
	@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解析结束");
	}
	
	/**
	 * 解析xml元素
	 */
	@Override
	public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
		//调用DefaultHandler类的startElement方法
		super.startElement(uri,localName,qName,attributes);
		if (qName.equals("book")) {
			bookIndex++;
			//创建一个book对象
			book = new Book();
			//开始解析book元素的属性
			System.out.println("======================开始遍历某一本书的内容=================");
//			//已知book元素下属性名称,根据属性名称获取属性值
//			String value = attributes.getValue("id");
//			System.out.println("book的属性值是:" + value);
			//不知道book元素下属性名称以及个数,如何获取属性名以及属性值
			int num = attributes.getLength();
			for(int i = 0; i < num; i++){
				System.out.print("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("name") && !qName.equals("bookstore")) {
			System.out.print("节点名是:" + qName + "---");
		}
	}
	
	@Override
	public void endElement(String uri,String qName)
			throws SAXException {
		//调用DefaultHandler类的endElement方法
		super.endElement(uri,qName);
		//判断是否针对一本书已经遍历结束
		if (qName.equals("book")) {
			bookList.add(book);
			book = null;
			System.out.println("======================结束遍历某一本书的内容=================");
		}
		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 characters(char[] ch,int start,int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch,start,length);
		value = new String(ch,length);
		if (!value.trim().equals("")) {
			System.out.println("节点值是:" + value);
		}
	}
}
package SAXCreateXml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

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 entity.Book;

public class SAXTestCreate {

	public void createXML() {
		Book b1 = new Book();
		b1.setId("1");
		b1.setName("冰与火之歌");
		b1.setAuthor("乔治马丁");
		b1.setYear("2014");
		b1.setPrice("89");
		Book b2 = new Book();
		b2.setId("2");
		b2.setName("安徒生童话");
		b2.setAuthor("乔治马丁");
		b2.setYear("2004");
		b2.setPrice("77");
		b2.setLanguage("English");
		ArrayList<Book> bookList = new ArrayList<Book>();
		bookList.add(b1);
		bookList.add(b2);
		// 生成xml
		// 1.创建一个TransformerFactory类的对象
		SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory
				.newInstance();
		try {
			// 2.通过SAXTransformerFactory对象创建一个TransformerHandler对象
			TransformerHandler handler = tff.newTransformerHandler();
			// 3.通过handler对象创建一个Transformer对象
			Transformer tr = handler.getTransformer();
//			// 4.通过Transformer对象对生成的xml文件进行设置
//			// 设置xml的编码
			tr.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
//			// 设置xml的“是否换行”
			tr.setOutputProperty(OutputKeys.INDENT,"yes");
			// 5.创建一个Result对象
			File f = new File("books2.xml");
			if (!f.exists()) {
				f.createNewFile();
			}
			// 6.创建Result对象,并且使其与handler关联
			Result result = new StreamResult(new FileOutputStream(f));
			handler.setResult(result);
			// 7.利用handler对象进行xml文件内容的编写O
			// 打开document
			handler.startDocument();
			AttributesImpl attr = new AttributesImpl();
			handler.startElement("","","bookstore",attr);
			
			for (Book book : bookList) {
				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(),book
							.getName().length());
					handler.endElement("","name");
				}
				// 创建year节点
				if (book.getYear() != null && !book.getYear().trim().equals("")) {
					attr.clear();
					handler.startElement("","year",attr);
					handler.characters(book.getYear().tocharArray(),book
							.getYear().length());
					handler.endElement("","year");
				}
				// 创建author节点
				if (book.getAuthor() != null && !book.getAuthor().trim().equals("")) {
					attr.clear();
					handler.startElement("","author",attr);
					handler.characters(book.getAuthor().tocharArray(),book
							.getAuthor().length());
					handler.endElement("","author");
				}
				// 创建price节点
				if (book.getPrice() != null && !book.getPrice().trim().equals("")) {
					attr.clear();
					handler.startElement("","price",attr);
					handler.characters(book.getPrice().tocharArray(),book
							.getPrice().length());
					handler.endElement("","price");
				}
				// 创建language节点
				if (book.getLanguage() != null && !book.getLanguage().trim().equals("")) {
					attr.clear();
					handler.startElement("","language",attr);
					handler.characters(book.getLanguage().tocharArray(),book
							.getLanguage().length());
					handler.endElement("","language");
				}
				handler.endElement("","book");
			}
			handler.endElement("","bookstore");
			// 关闭document
			handler.endDocument();

		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SAXTestCreate test = new SAXTestCreate();
		test.createXML();
	}

}
原文链接:https://www.f2er.com/xml/295182.html

猜你在找的XML相关文章