上一篇简单些了jdom解析xml文档,现在利用jdom生成一份xml文档 。当然需要上一篇中提到的Book.java,books.xml以及jdom2.0.6.zip.
生成xml文档代码:
CreateXMLFile.java
package com.wnq.sk.jdomXML01;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class CreateXMLFile
{
public static void main(String[] args)throws Exception
{
List<Book> books = JdomReadXMLFile.jdomReadXMLFile("books.xml");
String fileName = "jdom_create_books.xml";
createXMLFile(books, fileName);
}
public static void createXMLFile(List<Book> books, String fileName)
{
// 创建根节点
Element bookstoreElement = new Element("bookstore");
Document document = new Document(bookstoreElement);
// 创建book
for(int i=0;i<books.size();i++){
Element bookElement = new Element("book");
bookElement.setAttribute(new Attribute("category", books.get(i).getCategory()));
Element titleElement = new Element("title");
titleElement.setAttribute(new Attribute("lang", books.get(i).getTitleLang()));
titleElement.setText(books.get(i).getTitle());
bookElement.addContent(titleElement);
String[] author = books.get(i).getAuthor().split("/");
for (int j = 0; j < author.length; j++)
{
Element authorElement = new Element("author");
authorElement.setText(author[j]);
bookElement.addContent(authorElement);
}
Element yearElement = new Element("year");
yearElement.setText(books.get(i).getYear().toString());
bookElement.addContent(yearElement);
Element priceElement = new Element("price");
priceElement.setText(books.get(i).getPrice().toString());
bookElement.addContent(priceElement);
bookstoreElement.addContent(bookElement);
}
XMLOutputter xmlOutputter = new XMLOutputter(FormatXML());
try
{
xmlOutputter.output(document, new FileOutputStream(fileName));
System.out.println("JDOM生成XML文件成功");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// 格式化
public static Format FormatXML()
{
Format format = Format.getCompactFormat();
format.setEncoding("utf-8");
format.setIndent(" ");
return format;
}
}
生成的jdom_create_books.xml文档
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book category="cooking">
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.0</price>
</book>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>