浅析XML字符串和XML DOCUMENT的相互转换_Xml教程

编辑Tag赚U币
教程Tag:暂无Tag,欢迎添加,赚取U币!

推荐:XMLHTTP获取web访问头信息和网页代码
% Function BytesToBstr(body,Cset) dim objstream set objstream = Server.CreateObject(adodb.stream) objstream.Type = 1 objstream.Mode =3 objstream.Open objstream.Write body objstream.Position = 0 objstream.Type = 2 objstream.Charset = Cset

在做一般的XML数据交换过程中,我更乐意传递XML字符串,而不是格式化的XML Document。这就涉及到XML字符串和Xml Document的转换问题,说白了这是个很简单的问题,本文就各种XML解析器分别列举如下,以方便自己今后查阅。

  一、使用最原始的javax.xml.parsers,标准的jdk api

// 字符串转XML
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);

//XML转字符串
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();

这里的XML DOCUMENT为org.w3c.dom.Document

  二、使用dom4j后程序变得更简单

// 字符串转XML
String xmlStr = \"......\";
Document document = DocumentHelper.parseText(xmlStr);

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

这里的XML DOCUMENT为org.dom4j.Document

  三、使用JDOM

JDOM的处理方式和第一种方法处理非常类似

//字符串转XML
String xmlStr = \".....\";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
Document doc = (new SAXBuilder()).build(is);

//XML转字符串
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();

这里的XML DOCUMENT为org.jdom.Document

  四、JAVASCRIPT中的处理

//字符串转XML
var xmlStr = \".....\";
var xmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");
xmlDoc.async=false;
xmlDoc.loadXML(xmlStr);
//可以处理这个xmlDoc了
var name = xmlDoc.selectSingleNode(\"/person/name\");
alert(name.text);

//XML转字符串
var xmlDoc = ......;
var xmlStr = xmlDoc.xml

这里的XML DOCUMENT为javascript版的XMLDOM

 

分享:利用XML实现通用WEB报表打印实际使用中的例子
最近做的一个B/S项目,在打印时采用了在IE中嵌入.net winform控件和XML结合的方式(参见http://www.yesky.com/20030214/1652186.shtml),在实际应用过程中,有一些心得,和大家分享。 (一).使用通用模版格式化XML文件 系统中共用到了三种单据,分别为出库

来源:模板无忧//所属分类:Xml教程/更新时间:2010-03-28
相关Xml教程