greatjone

          BlogJava 聯系 聚合 管理
            7 Posts :: 24 Stories :: 3 Comments :: 0 Trackbacks

          具體代碼如下:

           1import java.io.FileNotFoundException;
           2import java.io.FileOutputStream;
           3import java.io.IOException;
           4
           5import org.jdom.Document;
           6import org.jdom.Element;
           7import org.jdom.output.XMLOutputter;
           8
           9
          10public class XMLWriter {
          11/*
          12     * 要輸出的文件格式為:
          13     * <books>
          14     *         <book>
          15     *             <name>蝸居</name>
          16     *             <price>30.00</price>
          17     *         </book>
          18     *         <book>
          19     *             <name>和空姐同居的日子</name>
          20     *             <price>25.00</price>
          21     *         </book>
          22     * <books>
          23     *利用JDOM對XML文件 進行寫操作,主要按以下步驟:
          24     *1.創建根元素
          25     *2.創建元素對象,利用addContent()方法為元素添加子元素或者文本值
          26     *3.創建Document對象
          27     *4.創建XMLOutputter對象,利用output()方法創建xml文件. 
          28     */

          29    public static void main(String[] args) throws Exception {
          30
          31        Element rootE = new Element("books");//創建根元素
          32        Element e1 = new Element("book");
          33        Element ename1 = new Element("name").addContent("蝸居");
          34        Element eprice1 = new Element("price").addContent("30.00");
          35        e1.addContent(ename1).addContent(eprice1);//添加子元素
          36        Element e2 = new Element("book");
          37        Element ename2 = new Element("name").addContent("和空姐同居的日子");
          38        Element eprice2 = new Element("price").addContent("25.00");
          39        e2.addContent(ename2).addContent(eprice2);        
          40        rootE.addContent(e1).addContent(e2);        
          41        Document d = new Document(rootE);//根據根元素創建Document,以便后續用        
          42        XMLOutputter xop = new XMLOutputter();//用來創建xml文件,輸出xml元素的
          43        xop.output(d, new FileOutputStream("C:/Documents and Settings/Administrator/桌面/book.xml"));
          44    }

          45
          46}
          posted on 2010-06-01 17:29 jone 閱讀(143) 評論(0)  編輯  收藏 所屬分類: xml

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 镇坪县| 中牟县| 海原县| 交城县| 高阳县| 邹平县| 娄烦县| 凯里市| 定南县| 衡山县| 思南县| 赤水市| 盐池县| 海晏县| 隆尧县| 湟源县| 龙门县| 饶平县| 岑巩县| 扶绥县| 婺源县| 沧州市| 汉源县| 咸丰县| 林口县| 太仆寺旗| 藁城市| 惠来县| 滦南县| 宝兴县| 五原县| 米林县| 阿巴嘎旗| 德昌县| 宜春市| 清远市| 堆龙德庆县| 巴东县| 元阳县| 大埔区| 乡宁县|