java中用jdom创建xml文档/将数据写入XML中
Posted ︶ㄣ霞光里
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中用jdom创建xml文档/将数据写入XML中相关的知识,希望对你有一定的参考价值。
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>
以上是关于java中用jdom创建xml文档/将数据写入XML中的主要内容,如果未能解决你的问题,请参考以下文章