1 dom 生成xml文档
上一篇已经介绍了如何解析xml文档,现在利用解析得到的数据生成一份xml文档(需要用到上一篇中的Book.java ReadXMLFile.java)。
2 生成xml文档的代码
CreateXML.java
package com.wnq.sk.domXML02;
import java.io.File;
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;
/**
* 生成xml文档
*
* @author liandong
*
*/
public class CreateXML
{
static String fileName = "dom_create_books.xml";
public static void main(String[] args)
{
List<Book> books = ReadXMLFile.readXMLFile("books.xml");
createXMLFile(books);
}
private static void createXMLFile(List<Book> books)
{
// 准备好创建xml文档所需要的Document 和 各元素
Document document;
Element bookstore, book, title, author, year, price;
DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder dBuilder = dBuilderFactory.newDocumentBuilder();
document = dBuilder.newDocument();
if (document != null)
{
bookstore = document.createElement("bookstore");
for (int i = 0; i < books.size(); i++)
{
book = document.createElement("book");
// 设置book的属性
book.setAttribute("catagory", books.get(i).getCategory());
title = document.createElement("title");
// 创建文本节点并作为子节点添加到title元素中
title.appendChild(document.createTextNode(books.get(i).getTitle()));
title.setAttribute("lang", books.get(i).getTitleLang());
book.appendChild(title);
String[] strAuthor = books.get(i).getAuthor().split("/");
for (int j = 0; j < strAuthor.length; j++)
{
author = document.createElement("author");
author.appendChild(document.createTextNode(strAuthor[j]));
book.appendChild(author);
}
year = document.createElement("year");
year.appendChild(document.createTextNode(books.get(i).getYear().toString()));
book.appendChild(year);
price = document.createElement("price");
price.appendChild(document.createTextNode(books.get(i).getPrice().toString()));
book.appendChild(price);
bookstore.appendChild(book);
}
document.appendChild(bookstore);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try
{
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult result = new StreamResult(new File(fileName));
try
{
transformer.transform(domSource, result);
}
catch (TransformerException e)
{
e.printStackTrace();
}
}
catch (TransformerConfigurationException e)
{
e.printStackTrace();
}
}
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
System.out.println("DOM成功创建XML文档!");
}
}
需要注意的地方就是,Node 的类型,可能是 ELEMRNT_NODE,TEXT_NODE......,不同类型的节点添加方式略有不同。
3 生成的xml文档截图如下
该贴被蜀山战纪编辑于2016-2-1 10:46:16