设为首页
优惠IDC
收藏本站
六狼博客
六狼论坛
开启辅助访问
切换到窄版
用户名
Email
自动登录
找回密码
密码
登录
立即注册
只需一步,快速开始
只需一步,快速开始
快捷导航
门户
首页
BBS
云计算
大数据
手机
移动开发android,ios,windows phone,windows mobile
编程
编程技术java,php,python,delphi,ruby,c,c++
前端
WEB前端htmlcss,javascript,jquery,html5
数据库
数据库开发Access,mysql,oracle,sql server,MongoDB
系统
操作系统windows,linux,unix,os,RedHat,tomcat
架构
项目管理
软件设计,架构设计,面向对象,设计模式,项目管理
企业
服务
运维实战
神马
搜索
搜索
热搜:
php
java
python
ruby
hadoop
sphinx
solr
ios
android
windows
centos
本版
帖子
用户
六狼论坛
»
首页
›
WEB前端
›
JavaScript
›
.XML字符串和XML DOCUMENT的相互转换
返回列表
查看:
68
|
回复:
0
.XML字符串和XML DOCUMENT的相互转换
[复制链接]
sxpyrgz
sxpyrgz
当前离线
积分
54
窥视卡
雷达卡
升级
2.67%
当前用户组为
秀才
当前积分为
54
, 升到下一级还需要 146 点。
12
主题
12
主题
12
主题
秀才
秀才, 积分 54, 距离下一级还需 146 积分
秀才, 积分 54, 距离下一级还需 146 积分
积分
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代码
回复
使用道具
举报
提升卡
置顶卡
沉默卡
喧嚣卡
变色卡
千斤顶
显身卡
返回列表
高级模式
B
Color
Image
Link
Quote
Code
Smilies
您需要登录后才可以回帖
登录
|
立即注册
本版积分规则
发表回复
回帖后跳转到最后一页
Copyright © 2008-2020
六狼论坛
(http://it.6wolf.com) 版权所有 All Rights Reserved.
Powered by
Discuz!
X3.4
京ICP备14020293号-2
本网站内容均收集于互联网,如有问题请联系
QQ:389897944
予以删除
快速回复
返回顶部
返回列表