1. 程式人生 > >String和Document相互轉換

String和Document相互轉換

一、使用最原始的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。