六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 68|回复: 0

.XML字符串和XML DOCUMENT的相互转换

[复制链接]

升级  2.67%

12

主题

12

主题

12

主题

秀才

Rank: 2

积分
54
 楼主| 发表于 2013-1-29 09:11:21 | 显示全部楼层 |阅读模式
一、使用最原始的javax.xml.parsers,标准的jdkapi
//字符串转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), newStreamResult(bos));
String xmlStr = bos.toString();

这里的XMLDOCUMENT为org.w3c.dom.Document
二、使用dom4j后程序变得更简单
//字符串转XML
String xmlStr = /"....../";
Document document = DocumentHelper.parseText(xmlStr);

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

这里的XMLDOCUMENT为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();

这里的XMLDOCUMENT为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

http://yhaiz.blog.163.com/blog/static/7889001120098244259554/

<span style="color: #000080; font-size: small;">2011-03-08 hongyz (初级程序员)

<div class="dp-highlighter"><div class="bar"><div class="tools">Java代码  
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表