JAVA操作JDOM

package src;

import java.io.*;

import org.jdom.*;

import org.jdom.output.*;

public class WritesXML

{

   public void BuildXML() throws Exception

   {

       Element root,student,number,name,age,s_list;

       root=new Element("student-info");//生成根元素:student-info 

       Document doc=new Document(root);   //將根元素植入文檔doc中

       s_list=new Element("s_list");
      
       s_list.setAttribute("count","5");
      
       root.addContent(s_list);
      
       for(int i=0;i<3;i++){
        student=new Element("student");     //生成元素:student,該元素中將包含元素number,name,age

           number=new Element("number");

           name=new Element("name");

           age=new Element("age");
          
           number.setText("001");

           name.setText("lnman");

           age.setText("24");
           student.addContent(number);

           student.addContent(name);

           student.addContent(age);
    
           s_list.addContent(student);
       }
      

       Format format=Format.getCompactFormat();

       format.setEncoding("gb2312");          //設置xml文件的字符爲gb2312

       format.setIndent("   ");              //設置xml文件的縮進爲4個空格

      

       XMLOutputter XMLOut=new XMLOutputter(format);//在元素後換行,每一層元素縮排四格

       XMLOut.output(doc,new FileOutputStream("studentinfo.xml"));

      

   }

  

   public static void main(String[]args)throws Exception

   {

       WritesXML w=new WritesXML();

       System.out.println("NowwebuildanXMLdocument.....");

       w.BuildXML();

       System.out.println("finished!");

   }

 

}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章