Java解析XML(二)、DOM

XML资源文件请见http://blog.csdn.net/xyang81/article/details/7247169

package xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import model.Book;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import util.DateUtils;

/**
 * 使用DOM读写XML
 * @author 杨信
 *
 */
public class DomHelper {
	
	private static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	
	/**
	 * 使用DOM解析XML
	 * @param is XML文件输入流
	 * @return 解析后的数据
	 */
	public static List<Book> domReader(InputStream is) {
		List<Book> books = null;
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(is);
			Element rootElement = document.getDocumentElement();
			NodeList nodes = rootElement.getElementsByTagName("book");
			if (nodes != null && nodes.getLength() > 0) {
				books = new ArrayList<Book>();
				for(int i = 0; i < nodes.getLength(); i++) {
					/*//获得节点方式1
					Node node = nodes.item(i);
					book.setIsbn(node.getAttributes().item(0).getNodeValue());	//获得book节点ISBN属性的值
					//获得book节点下的所有子节点
					NodeList bookChildList = node.getChildNodes();*/
					//获得节点方式2
					Book book = new Book();
					Element bookElement = (Element) nodes.item(i);
					book.setIsbn(bookElement.getAttribute("isbn"));	//获得book节点ISBN属性的值
					NodeList bookChildList = bookElement.getChildNodes();
					for(int j = 0; j < bookChildList.getLength(); j++) {
						Node childNode = bookChildList.item(j);
						if (childNode.getNodeType() == Node.ELEMENT_NODE) {	//判断当前节点类型,是否为一个元素节点.(节点类型分:Element和Text节点.)
							String nodeName = childNode.getNodeName();
							String nodeValue = childNode.getTextContent();
							if ("name".equals(nodeName)) {
								book.setName(nodeValue);
							} else if ("author".equals(nodeName)) {
								book.setAuthor(nodeValue);
							} else if ("publishing".equals(nodeName)) {
								book.setPublishing(nodeValue);
							} else if ("pubdate".equals(nodeName)) {
								book.setPubdate(DateUtils.string2Date("yyyy-mm-dd", nodeValue));
							} else if ("price".equals(nodeName)) {
								book.setPrice(Double.parseDouble(nodeValue));
							}
						}
					}
					books.add(book);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return books;
	}

	/**
	 * 使用dom写xml文件
	 * @param books 数据
	 * @param outfile xml文件保存位置
	 */
	public static void domWriter(List<Book> books,File outfile) {
		Document doc = null;
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.newDocument();
			Element booksElement = doc.createElement("books");
			for (Book book : books) {
				//创建一本图书
				Element bookElement = doc.createElement("book");
				//设置图片的编号
				bookElement.setAttribute("isbn", book.getIsbn());
				//书名
				Element nameElement = doc.createElement("name");
				nameElement.setTextContent(book.getName());
				bookElement.appendChild(nameElement);
				//作者
				Element authorElement = doc.createElement("author");
				authorElement.setTextContent(book.getAuthor());
				bookElement.appendChild(authorElement);
				//出版社
				Element publishingElement = doc.createElement("publishing");
				publishingElement.setTextContent(book.getPublishing());
				bookElement.appendChild(publishingElement);
				//出版日期
				Element pubdateElement = doc.createElement("pubdate");
				pubdateElement.setTextContent(DateUtils.date2String("yyyy-mm-dd", book.getPubdate()));
				bookElement.appendChild(pubdateElement);
				//价格
				Element priceElement = doc.createElement("price");
				priceElement.setTextContent(String.valueOf(book.getPrice()));
				bookElement.appendChild(priceElement);
				//将每本书添加到根节点中
				booksElement.appendChild(bookElement);
			}
			doc.appendChild(booksElement);
			//将数据生成xml文件
			FileOutputStream fos = new FileOutputStream(outfile);
			OutputStreamWriter outwriter = new OutputStreamWriter(fos);
			callWriteXmlFile(doc, outwriter, "gb2312");
			outwriter.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 定入xml文件
	 * @param doc xml文档对象
	 * @param w 写xml文件的字符流对象
	 * @param encoding xml编码
	 */
	public static void callWriteXmlFile(Document doc, Writer w, String encoding) {
		try {
			Source source = new DOMSource(doc);
			Result result = new StreamResult(w);
			Transformer xformer = TransformerFactory.newInstance().newTransformer();
			xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
			xformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

}
posted @ 2012-02-10 21:12  奋斗+坚持  阅读(141)  评论(0编辑  收藏  举报