java XML字串和XML DOCUMENT的相互轉換

來源:互聯網
上載者:User
 

在做一般的XML資料交換過程中,我更樂意傳遞XML字串,而不是格式化的XML Document。這就涉及到XML字串和Xml Document的轉換問題,說白了這是個很簡單的問題,本文就各種XML解析器分別列舉如下,以方便自己今後查閱。

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

轉自:http://blog.csdn.net/yhl_621/article/details/614960

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.