Document对象转String,简单记录一下!
Code1:
package com.project.util;import java.io.IOException;import java.io.StringWriter;import org.apache.log4j.Logger;import org.w3c.dom.Document;import com.sun.org.apache.xml.internal.serialize.OutputFormat;import com.sun.org.apache.xml.internal.serialize.XMLSerializer;public class DocumentUtil { public static Logger log = Logger.getLogger(DocumentUtil.class.getClass()); /** * Document 转换为 String 并且进行了格式化缩进 * * @param doc XML的Document对象 * @return String */ public static String doc2FormatString(Document doc) { String docString = ""; if(doc != null){ StringWriter stringWriter = new StringWriter(); try{ OutputFormat format = new OutputFormat(doc,"UTF-8",true); //format.setIndenting(true);//设置是否缩进,默认为true //format.setIndent(4);//设置缩进字符数 //format.setPreserveSpace(false);//设置是否保持原来的格式,默认为 false //format.setLineWidth(500);//设置行宽度 XMLSerializer serializer = new XMLSerializer(stringWriter,format); serializer.asDOMSerializer(); serializer.serialize(doc); docString = stringWriter.toString(); }catch(Exception e){ e.printStackTrace(); }finally{ if(stringWriter != null){ try { stringWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } log.error("XML内容:"+docString); return docString; } }
Code2:
/** * org.w3c.dom.Document 转换为 String * * @param org.w3c.dom.Document对象 * @return String */ public static String docToString(Document doc) { String docStr = ""; if(doc!=null){ try{ TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("encoding", "UTF-8"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); transformer.transform(new DOMSource(doc), new StreamResult(outputStream)); //docStr = outputStream.toString(); docStr = outputStream.toString("UTF-8"); System.out.println("\n********************** 【org.w3c.dom.Document对象转XML字符串内容:】 **********************\n"+docStr); }catch(Exception e){ e.printStackTrace(); } } return docStr; }