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();
		}
	}

}

转载于:https://www.cnblogs.com/xyang0917/archive/2012/02/10/4172542.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值