本文實(shí)例講述了java生成xml格式文件的方法。分享給大家供大家參考,具體如下:
這里演示利用Java生成xml格式文件
Demo中所用到的jar包Jdom.jar 。
為了方便理解,我寫了個(gè)Demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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" , "唐詩(shī)三百首" ), 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ì)有所幫助。