[java]代码库
package com.read.xml;
import java.io.IOException;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class WriteXml {
public static String readXml(){
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
Element name = root.addElement("name");
name.setText("张三");
Element age = root.addElement("age");
age.setText("12");
Element sex = root.addElement("sex");
sex.setText("男");
// String docString = formatXml(doc, "GBK", false);
String docString = formatXml(doc, "GBK", true);
// String docString =doc.asXML();
return docString;
}
/**
* 格式化XML文档
*
* @param document xml文档
* @param charset 字符串的编码
* @param istrans 是否对属性和元素值进行转移
* @return 格式化后XML字符串
*/
public static String formatXml(Document document, String charset, boolean istrans) {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(charset);
format.setSuppressDeclaration(istrans); //去掉xml的标题头,如<?xml version="1.0" encoding="GBK"?>
StringWriter sw = new StringWriter();
XMLWriter xw = new XMLWriter(sw, format);
xw.setEscapeText(istrans);
try {
xw.write(document);
xw.flush();
xw.close();
} catch (IOException e) {
System.out.println("格式化XML文档发生异常,请检查!");
e.printStackTrace();
}
return sw.toString();
}
public static void main(String[] args){
System.out.println(readXml());
}
}