本次學習的是利用java產生xml格式檔案
Demo中所用到的jar包Jdom.jar
為了方便理解,我寫了個Demo
本文來自 http://blog.csdn.net/manymore13
import java.io.FileOutputStream;import java.io.IOException;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.output.Format;import org.jdom.output.XMLOutputter; public class Java2XML {Book[] books = new Book[]{new Book("1","唐詩三百首"),new Book("2","Think in Java"),new Book("3","神鵰俠侶"),new Book("4","葵花寶典")}; public void BuildXMLDoc() throws IOException, JDOMException { // 建立根節點 並設定它的屬性 ; Element root = new Element("books").setAttribute("count", "4"); // 將根節點添加到文檔中; Document Doc = new Document(root); for (int i = 0; i < books.length; i++) { // 建立節點 book; Element elements = new Element("book"); // 給 book 節點添加子節點並賦值; elements.addContent(new Element("id").setText(books[i].getBook_id())); elements.addContent(new Element("name").setText(books[i].getBook_name())); // root.addContent(elements); } // 輸出 books.xml 檔案; // 使xml檔案 縮排效果 Format format = Format.getPrettyFormat(); XMLOutputter XMLOut = new XMLOutputter(format); XMLOut.output(Doc, new FileOutputStream("c:/books.xml")); } public static void main(String[] args) { try { Java2XML j2x = new Java2XML(); System.out.println("正在產生 books.xml 檔案..."); j2x.BuildXMLDoc(); } catch (Exception e) { e.printStackTrace(); } System.out.println("c:/books.xml 檔案已產生"); } }
運行效果是在本人電腦c盤有個books.xml檔案(此前是沒有這個檔案)
簡單Demo 一看就清楚