package java_xml.dom_test;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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;
public class DomXmlCreate {
private List bookList=new ArrayList();
/**
* 向bookList添加Book对象;
*/
public void bookListAdd(){
Book book1=new Book("1","鬼吹灯","天下霸唱",2000,90.0,"中文");
Book book2=new Book("2","Go with Wind","CPN",2000,90.0,"English");
Book[] bookArray={book1,book2};
bookList.addAll(Arrays.asList(bookArray));
// for (Book book : bookList) {
// System.out.println(book);
// }
}
/**
* 将bookList中的对象导入生成Xml文件的方法
*/
public void CreateXML(){
//创建document对象
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db=dbf.newDocumentBuilder();
Document document=db.newDocument();
//向document添加根节点
Element bookStore=document.createElement("bookStore");
document.setXmlStandalone(true);
bookStore.setAttribute("id", "1");
//使用循环将bookList中的book对象通过创建节点弄进去document对象
for(Book a:bookList){
Element book=document.createElement("book");
book.setAttribute("id", a.getId());
bookStore.appendChild(book);
Element name=document.createElement("name");
name.setTextContent(a.getName());
book.appendChild(name);
Element author=document.createElement("author");
author.setTextContent(a.getAuthor());
book.appendChild(author);
Element year=document.createElement("year");
year.setTextContent(Integer.toString(a.getYear()));
book.appendChild(year);
Element price=document.createElement("price");
price.setTextContent(Double.toString(a.getPrice()));
book.appendChild(price);
Element language=document.createElement("language");
language.setTextContent(a.getLanguage());//创建book及其所有子节点
book.appendChild(language);
}
//将document对象进行输出xml文件
TransformerFactory tfF=TransformerFactory.newInstance();
Transformer tf=tfF.newTransformer();
//tf.setOutputProperty(OutputKeys.INDENT,"yes");
tf.transform(new DOMSource(document), new StreamResult(new File("src/java_xml/dom_test/bookTest.xml")));
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DomXmlCreate d1=new DomXmlCreate();
d1.bookListAdd();
d1.CreateXML();
}
}