关于XML字符串和XML Document之间的转换

  在web项目中,XML作为一种重要的数据存储和传输介质,被广泛使用。XML文件,XML字符串和XML Document对象是XML存在的三种形式,XML文件无需多言,和普通的文本并无二致;倒是在做一般的XML数据交换过程中,经常要使用XML字符串和XML Document对象,因此在这两种形式之间进行转化成为了使用XML的必备技术。在所有操控XML的技术中,都提供了这两种形式XML之间的转换方法。
  下面我就各种XML技术对此问题的解决方法做个总结,和大家分享,也方便自己今后查阅。
一,使用JDOM(这是我最常使用的一种技术)
  1.字符串转Document对象
String xmlStr = ".....";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
Document doc = (new SAXBuilder()).build(is);
  2.Document对象转字符串
Format format = Format.getPrettyFormat();
format.setEncoding("gb2312");//设置xml文件的字符为gb2312,解决中文问题
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
xmlout.output(doc,bo);
String xmlStr = bo.toString();
 注:Document为org.jdom.Document

二,使用最原始的javax.xml.parsers,标准的jdk api
  1.字符串转Document对象
String xmlStr = "......";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(is);
  2.Document对象转字符串
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("encoding","GB23121");//解决中文问题,试过用GBK不行
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
String xmlStr = bos.toString();
 注:Document为org.w3c.dom.Document

三,使用dom4j(这是最简单的方法)
  1.字符串转Document对象
String xmlStr = "......";
Document document = DocumentHelper.parseText(xmlStr);
  2.Document对象转字符串
Document document = ...;
String text = document.asXML();
 注:Document为org.dom4j.Document

四,在JavaScript中的处理
 1.字符串转Document对象
var xmlStr = ".....";
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(xmlStr);
//可以处理这个xmlDoc了
var name = xmlDoc.selectSingleNode("/person/name");
alert(name.text);
  2.Document对象转字符串
var xmlDoc = ......;
var xmlStr = xmlDoc.xml
 注:Document为javaScript版的XMLDOM
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值