greatjone

          BlogJava 聯(lián)系 聚合 管理
            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對(duì)XML文件 進(jìn)行寫操作,主要按以下步驟:
          24     *1.創(chuàng)建根元素
          25     *2.創(chuàng)建元素對(duì)象,利用addContent()方法為元素添加子元素或者文本值
          26     *3.創(chuàng)建Document對(duì)象
          27     *4.創(chuàng)建XMLOutputter對(duì)象,利用output()方法創(chuàng)建xml文件. 
          28     */

          29    public static void main(String[] args) throws Exception {
          30
          31        Element rootE = new Element("books");//創(chuàng)建根元素
          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);//根據(jù)根元素創(chuàng)建Document,以便后續(xù)用        
          42        XMLOutputter xop = new XMLOutputter();//用來(lái)創(chuàng)建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 閱讀(141) 評(píng)論(0)  編輯  收藏 所屬分類: xml

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 连江县| 太仆寺旗| 剑河县| 厦门市| 教育| 防城港市| 逊克县| 洛宁县| 策勒县| 临邑县| 通海县| 都匀市| 武穴市| 井研县| 三河市| 蒙阴县| 柞水县| 疏附县| 达日县| 大厂| 大石桥市| 伊春市| 正定县| 旬阳县| 长沙县| 长乐市| 泽普县| 冷水江市| 宝丰县| 格尔木市| 蒙山县| 宜阳县| 斗六市| 黔西县| 安徽省| 民权县| 思茅市| 布尔津县| 庐江县| 遂平县| 靖边县|