String 和 document 的相互转换总结
来源:互联网 发布:mysql查询笔试题及答案 编辑:程序博客网 时间:2024/06/05 08:32
一、使用最原始的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。
- String 和 document 的相互转换总结
- String 和 document 的相互转换总结
- String 和 document 的相互转换总结
- XML String字符串 和 document 的相互转换总结 .
- String 和 document 的相互转换
- dom4j 和w3c document 的相互转换
- dom4j 和w3c document 的相互转换
- int,String,Integer相互转换的总结
- XML字符串和XML DOCUMENT的相互转换
- XML字符串和XML DOCUMENT的相互转换
- XML字符串和XML DOCUMENT的相互转换
- XML字符串和XML DOCUMENT的相互转换
- XML字符串和XML DOCUMENT的相互转换
- XML字符串和XML DOCUMENT的相互转换
- XML字符串和XML DOCUMENT的相互转换
- XML字符串和XML DOCUMENT的相互转换【转】
- XML字符串和XML DOCUMENT的相互转换
- java XML字符串和XML DOCUMENT的相互转换
- 常用存储过程集锦
- hibernate面试题 --- load()和get()方法的区别
- 计算1到100以内前5个能被3整除的数字
- 用java实现换位法生成全排列
- 关于使用ETL工具Kettle的简单介绍(一)
- String 和 document 的相互转换总结
- 一个巧妙的自定义UITableViewCell的办法
- 如何查看common lisp函数的文档?
- 广义容斥原理
- SQL SERVER STATISTICS
- Visual Studio error C4335: 检测到 Mac 文件格式: 请将源文件转换为 DOS 格式或 UNIX 格式解决
- jar依赖版本不一致导致的诡异情况
- 变量前面没有加数据类型出现的错误。
- 说出来不好意思:从学C++开始,到现在8年了,才知道的using还有这种用法。