java產生xml格式檔案的方法_java

來源:互聯網
上載者:User

本文執行個體講述了java產生xml格式檔案的方法。分享給大家供大家參考,具體如下:

這裡示範利用Java產生xml格式檔案

Demo中所用到的jar包Jdom.jar 。

為了方便理解,我寫了個Demo

import java.io.FileOutputStream;import java.io.IOException;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;public class Java2XML {  Book[] books = new Book[]  {      new Book("1","唐詩三百首"),      new Book("2","Think in Java"),      new Book("3","神鵰俠侶"),      new Book("4","葵花寶典")  };  public void BuildXMLDoc() throws IOException, JDOMException {    // 建立根節點 並設定它的屬性 ;    Element root = new Element("books").setAttribute("count", "4");    // 將根節點添加到文檔中;    Document Doc = new Document(root);    for (int i = 0; i < books.length; i++) {      // 建立節點 book;      Element elements = new Element("book");      // 給 book 節點添加子節點並賦值;      elements.addContent(new Element("id").setText(books[i].getBook_id()));      elements.addContent(new Element("name").setText(books[i].getBook_name()));      //      root.addContent(elements);    }    // 輸出 books.xml 檔案;    // 使xml檔案 縮排效果    Format format = Format.getPrettyFormat();    XMLOutputter XMLOut = new XMLOutputter(format);    XMLOut.output(Doc, new FileOutputStream("c:/books.xml"));  }  public static void main(String[] args) {    try {      Java2XML j2x = new Java2XML();      System.out.println("正在產生 books.xml 檔案...");      j2x.BuildXMLDoc();    } catch (Exception e) {      e.printStackTrace();    }    System.out.println("c:/books.xml 檔案已產生");  }}

運行效果是在本人電腦c盤有個books.xml檔案(此前是沒有這個檔案)

簡單Demo 一看就清楚

希望本文所述對大家java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.