---
title: "xml 字符串和xml Document相互转换、xml Document内容输出到http response"
author: "desert3"
date: "2012-11-05T10:07:51Z"
tags: []
categories: ["企业架构"]
slug: "xml-xml-document-xml-document-http-response"
draft: false
lastmod: "2012-11-05T10:12:55Z"
id: 1716464
url: "https://desert3.iteye.com/blog/1716464"
---

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

```

当xmlStr的内容为aa时，系统会报错误：  :1:1: Content is not allowed in prolog.
当xmlStr的内容为<xml>content</xml>bb时，系统会报错误 :1:19: Content is not allowed in trailing section.
都是提示<span style="color:blue">:m：n，m行n列所在位置的内容不是正常的xml内容</span>

参考：[XML字符串和XML DOCUMENT的相互转换(](http://lwbpeter.blog.163.com/blog/static/385082112010103112216129/)