java生成xml格式文件的方法
本文實(shí)例講述了java生成xml格式文件的方法。分享給大家供大家參考,具體如下:
這里演示利用Java生成xml格式文件
Demo中所用到的jar包Jdom.jar 。
為了方便理解,我寫了個(gè)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é)點(diǎn) 并設(shè)置它的屬性 ; Element root = new Element("books").setAttribute("count", "4"); // 將根節(jié)點(diǎn)添加到文檔中; Document Doc = new Document(root); for (int i = 0; i < books.length; i++) { // 創(chuàng)建節(jié)點(diǎn) book; Element elements = new Element("book"); // 給 book 節(jié)點(diǎn)添加子節(jié)點(diǎn)并賦值; 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文件 縮進(jìn)效果 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 文件已生成"); } }
運(yùn)行效果是在本人電腦c盤有個(gè)books.xml文件(此前是沒有這個(gè)文件)
簡(jiǎn)單Demo 一看就清楚
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章
Java超詳細(xì)分析講解final關(guān)鍵字的用法
關(guān)于final關(guān)鍵字,它也是我們一個(gè)經(jīng)常用的關(guān)鍵字,可以修飾在類上、或者修飾在變量、方法上,以此看來定義它的一些不可變性!像我們經(jīng)常使用的String類中,它便是final來修飾的類,并且它的字符數(shù)組也是被final所修飾的。但是一些final的一些細(xì)節(jié)你真的了解過嗎2022-06-06Spring負(fù)載均衡LoadBalancer使用詳解
這篇文章主要介紹了Spring負(fù)載均衡LoadBalancer使用詳解,Spring Cloud LoadBalancer是Spring Cloud官方自己提供的客戶端負(fù)載均衡器, 用來替代Ribbon,Spring官方提供了兩種客戶端都可以使用loadbalancer,需要的朋友可以參考下2023-11-11Java之a(chǎn)pi網(wǎng)關(guān)斷言及過濾器案例講解
這篇文章主要介紹了Java之a(chǎn)pi網(wǎng)關(guān)斷言及過濾器案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08SpringBoot整合mybatis通用Mapper+自定義通用Mapper方法解析
這篇文章主要介紹了SpringBoot整合mybatis通用Mapper+自定義通用Mapper方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03MybatisPlus實(shí)現(xiàn)邏輯刪除功能
這篇文章主要介紹了MybatisPlus實(shí)現(xiàn)邏輯刪除功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12