(9条消息) Java Document对象转String_weixin_33860147的博客-CSDN博客
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;
}
String 转 Document
org.w3c.dom document 和xml 字符串 互转 - Sharpest - 博客园 (cnblogs.com)
/**
* 将传入的一个XML String转换成一个org.w3c.dom.Document对象返回。
*
* @param xmlString
* 一个符合XML规范的字符串表达。
* @return a Document
*/
public static Document parseXMLDocument(String xmlString) {
if (xmlString == null) {
throw new IllegalArgumentException();
}
try {
return newDocumentBuilder().parse(
new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}