建立XML文檔並儲存到磁碟檔案中(GBK)

來源:互聯網
上載者:User
package com.bjpowernodetest;import java.io.FileWriter;import java.io.IOException;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;import junit.framework.TestCase;/** *  * @author Kevin * 建立XML文檔並儲存到磁碟檔案中(GBK) */public class TestXMLWriter extends TestCase {/**<?xml version="1.0" encoding="UTF-8"?> <items> <item> <id>10003</id> <name>保定</name> </item> <item> <id>10004</id> <name>天津</name> </item> </items> *//** * 建立上述的XML */public void testXMLWriter() {// 建立XML文檔樹Document document = DocumentHelper.createDocument();// 建立根節點itemsElement itemsElement = document.addElement("items");// 建立根節點下的item子節點Element itemElement = itemsElement.addElement("item");// item節點有兩個子節點Element idElement = itemElement.addElement("id");idElement.setText("10003");Element nameElement = itemElement.addElement("name");nameElement.setText("保定");// 設定XML文檔格式,漂亮的格式OutputFormat outputFormat = OutputFormat.createPrettyPrint();// 設定XML編碼方式,即是用指定的編碼方式儲存XML文檔到檔案,並讓瀏覽器用指定的編碼方式解析XML文檔outputFormat.setEncoding("GBK");try {// xmlWriter對應磁碟的一個檔案(Test.xml),此處(GBK編碼)要用FileWriter,否則可能導致亂碼,比如用FileOutputStream,會導致亂碼XMLWriter xmlWriter = new XMLWriter(new FileWriter("C:/Test.xml"), outputFormat);// 把建立好的XML文檔寫入檔案xmlWriter.write(document);xmlWriter.close();System.out.println("把XML文檔寫入檔案成功!");} catch (IOException e) {e.printStackTrace();throw new RuntimeException("把XML文檔寫入檔案失敗!");}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.