java生成xml格式文件的方法
更新時間:2016年07月08日 16:35:02 作者:manymore13
這篇文章主要介紹了java生成xml格式文件的方法,涉及java節(jié)點遍歷與屬性操作的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了java生成xml格式文件的方法。分享給大家供大家參考,具體如下:
這里演示利用Java生成xml格式文件
Demo中所用到的jar包Jdom.jar 。
為了方便理解,我寫了個Demo
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 {
// 創(chuàng)建根節(jié)點 并設(shè)置它的屬性 ;
Element root = new Element("books").setAttribute("count", "4");
// 將根節(jié)點添加到文檔中;
Document Doc = new Document(root);
for (int i = 0; i < books.length; i++) {
// 創(chuàng)建節(jié)點 book;
Element elements = new Element("book");
// 給 book 節(jié)點添加子節(jié)點并賦值;
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 一看就清楚
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
Java之a(chǎn)pi網(wǎng)關(guān)斷言及過濾器案例講解
這篇文章主要介紹了Java之a(chǎn)pi網(wǎng)關(guān)斷言及過濾器案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08
SpringBoot整合mybatis通用Mapper+自定義通用Mapper方法解析
這篇文章主要介紹了SpringBoot整合mybatis通用Mapper+自定義通用Mapper方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

