xml 字符串和xml Document相互转换、xml Document内容输出到http response


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Test {

/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) {
try {
// 使用最原始的javax.xml.parsers,标准的jdk api
// 字符串转XML
String xmlStr = "content";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(is);

// XML转字符串
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
// 编码设置
t.setOutputProperty("encoding", "GB2312");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
xmlStr = bos.toString();

// 把org.w3c.dom.Document doc的xml内容输出到http response
response.setContentType("text/xml");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 1);

DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(response.getOutputStream());

t.transform(source, result);
} catch (Exception e) {
System.out.println(e.getMessage());
}


// 使用dom4j后程序变得更简单
// 字符串转XML
String xmlStr1 = "content1";
org.dom4j.Document.Document document = DocumentHelper.parseText(xmlStr1);

// XML转字符串
org.dom4j.Document.Document document = ...;
String text = document.asXML();
}
}

当xmlStr的内容为aa时,系统会报错误: [Fatal Error] :1:1: Content is not allowed in prolog.
当xmlStr的内容为contentbb时,系统会报错误[Fatal Error] :1:19: Content is not allowed in trailing section.
都是提示[color=blue]:m:n,m行n列所在位置的内容不是正常的xml内容[/color]

参考:[url=http://lwbpeter.blog.163.com/blog/static/385082112010103112216129/]XML字符串和XML DOCUMENT的相互转换([/url]

你可能感兴趣的:(Java)