基于dom4j的XML格式转化类 package com.lixi.util; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import org.dom4j.Document; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; /** * <p>Title: </p> * <p>Description: XML格式转化工具</p> * <p>Copyright: Copyright (c) 2010-02-05</p> * <p>Company: </p> * @author li.xi * @version 1.0 */ public class XmlHelper { public XmlHelper() { } /** * String格式的XML转Document * @param xml * @param charSet 字符集编码设置 如:GBK * @return Document * @throws Exception */ public static Document buildDoc(String xml, String charSet) throws Exception { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); SAXReader reader = new SAXReader(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream, charSet); Document document = reader.read(inputStreamReader); inputStreamReader.close(); return document; } /** * Document格式的XML转String * @param document * @param charSet 字符集编码设置 * @return String * @throws Exception */ public static String setCharSet(Document document, String charSet) throws Exception { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(charSet); ByteArrayOutputStream fos = new ByteArrayOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, charSet)); XMLWriter writer = new XMLWriter(bw, format); writer.write(document); bw.close(); String restr = fos.toString(); fos.close(); return restr; } }