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


一, 使用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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM