jdk工具类____xml解析Dom解析
package com.cnse.test;
import java.util.Date;
/**
* 图书
*/
public class Book {
/**
* 图书编号
*/
private String isbn;
/**
* 书名
*/
private String name;
/**
* 作者
*/
private String author;
/**
* 出版社
*/
private String publishing;
/**
* 发布时间
*/
private Date pubdate;
/**
* 价格
*/
private double price;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
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 getPublishing() {
return publishing;
}
public void setPublishing(String publishing) {
this.publishing = publishing;
}
public Date getPubdate() {
return pubdate;
}
public void setPubdate(Date pubdate) {
this.pubdate = pubdate;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return "name: " + name + " isbn: " + isbn + " author: " + author
+ " publishing: " + publishing + " pubdate: " + pubdate
+ " price: " + price;
}
}
//
package com.cnse.test;
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.Date;
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 org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* 使用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(new Date());
} 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(String.valueOf(new Date().getHours()));
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();
}
}
}
//
package com.cnse.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DomTest {
public static void main(String[] args) {
DomHelper domHelper=new DomHelper();
Book books=new Book();
books.setAuthor("zhangsan");
books.setIsbn("asdsd");
books.setName("sdfasd");
books.setPrice(10.00);
books.setPubdate(new Date());
books.setPublishing("12242342");
List list=new ArrayList();
list.add(books);
domHelper.domWriter(list, new File("test.xml"));
}
}
//
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<books>
<book isbn="asdsd">
<name>sdfasd</name>
<author>zhangsan</author>
<publishing>12242342</publishing>
<pubdate>14</pubdate>
<price>10.0</price>
</book>
</books>