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 = "<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时,系统会报错误: [Fatal Error] :1:1: Content is not allowed in prolog.
当xmlStr的内容为<xml>content</xml>bb时,系统会报错误[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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值