import java.io.File;
import java.io.FileWriter;
import java.io.IOException; html
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter; java
/**
* @Copyright @ 2012 All right reserved
* @version 建立時間:Created on 2012-12-20
* @author 做者:Create by www.360buyli.com
* @Email : 360buyli@gmail.com
* @description 用於操做xml
*/ 框架
public class XmlUtil {
public void generateDocument() {
Document document = DocumentHelper.createDocument();
Element catalogElement = document.addElement("catalog");
catalogElement.addComment("An XML Catalog");
catalogElement.addProcessingInstruction("target", "text");
Element journalElement = catalogElement.addElement("student");
journalElement.addAttribute("stuName", "張三");
Element clsElement=journalElement.addElement("class");
clsElement.addAttribute("claName","電氣一班");
document.addDocType("catalog", null, "file://c:/Dtds/catalog.dtd");
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GB2312");
XMLWriter output = new XMLWriter(new FileWriter(new File("c:/catalog.xml")),format);
output.write(document);
output.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
} dom
public static void main(String[] argv) {
XmlUtil dom4j = new XmlUtil();
dom4j.generateDocument();
} 編碼
}
每每操做文件並非實現自己,而是在操做文本是碰到的亂碼問題。操做xml這樣的文本文件一樣會存在亂碼問題。剛開始沒有加紅色加粗部分時,寫出來的xml文件徹底是沒有格式化的,仍是就是中文亂碼。從類的命名,能夠看出這個處理對輸入的格式化。後面的設置編碼也正好解決了亂碼的問題 spa