DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
XML 字串與 XML Document 的雙向轉換
編輯:XML詳解     

在一般的 XML 資料交換中,我更樂意傳遞 XML 字串,而非格式化的 XML 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", "GB2312"); // 解決中文問題,試過用 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。掌握這幾種寫法,日後在 Java 或瀏覽器端做資料交換時就能隨手取用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved