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// 字符串转XMLString xmlStr = "<xml>content</xml>";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后程序变得更简单// 字符串转XMLString xmlStr1 = "<xml>content1</xml>";org.dom4j.Document.Document document = DocumentHelper.parseText(xmlStr1);// XML转字符串 org.dom4j.Document.Document document = ...;String text = document.asXML();}}