java中用jdom建立xml文件/將資料寫入XML中
阿新 • • 發佈:2018-11-14
1 import java.io.FileNotFoundException; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 6 import org.jdom.Attribute; 7 import org.jdom.Comment; 8 import org.jdom.Document; 9 import org.jdom.Element; 10 import org.jdom.output.Format; 11 import org.jdom.output.XMLOutputter;12 13 public class JDomOutput 14 { 15 public static void main(String[] args) throws IOException 16 { 17 //建立文件 18 Document document = new Document(); 19 //建立根元素 20 Element people = new Element("people"); 21 //把根元素加入到document中 22 document.addContent(people);23 24 //建立註釋 25 Comment rootComment = new Comment("將資料從程式輸出到XML中!"); 26 people.addContent(rootComment); 27 28 //建立父元素 29 Element person1 = new Element("person"); 30 //把元素加入到根元素中 31 people.addContent(person1); 32 //設定person1元素屬性33 person1.setAttribute("id", "001"); 34 35 Attribute person1_gender = new Attribute("gender", "male"); 36 person1.setAttribute(person1_gender); 37 38 Element person1_name = new Element("name"); 39 person1_name.setText("劉德華"); 40 person1.addContent(person1_name); 41 42 Element person1_address = new Element("address"); 43 person1_address.setText("香港"); 44 person1.addContent(person1_address); 45 46 47 Element person2 = new Element("person"); 48 people.addContent(person2); 49 50 person2.setAttribute("id", "002").setAttribute("gender","male");//新增屬性,可以一次新增多個屬性 51 52 Element person2_name = new Element("name"); 53 person2_name.setText("林志穎"); 54 person2.addContent(person2_name); 55 56 Element person2_address = new Element("address"); 57 person2_address.setText("臺灣"); 58 person2.addContent(person2_address); 59 60 61 //設定xml輸出格式 62 Format format = Format.getPrettyFormat(); 63 format.setEncoding("utf-8");//設定編碼 64 format.setIndent(" ");//設定縮排 65 66 67 //得到xml輸出流 68 XMLOutputter out = new XMLOutputter(format); 69 //把資料輸出到xml中 70 out.output(document, new FileOutputStream("jdom.xml"));//或者FileWriter 71 72 } 73 74 }
---------------------------------------------------------------------------------------------------------------------------
生成的xml內容如下:
----------------------------------------------------------------------------------------------------------------------------
1 <?xml version="1.0" encoding="utf-8"?> 2 <people> 3 <!--將資料從程式輸出到XML中!--> 4 <person id="001" gender="male"> 5 <name>劉德華</name> 6 <address>香港</address> 7 </person> 8 <person id="002" gender="male"> 9 <name>林志穎</name> 10 <address>臺灣</address> 11 </person> 12 </people>