java解析xml文件

       XML現在已經成爲一種通用的數據交換格式,它的平臺無關性,語言無關性,系統無關性,給數據集成與交互帶來了極大的方便。對於XML本身的語法知識與技術細節,需要閱讀相關的技術文獻,這裏麪包括的內容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transformations),具體可參閱w3c官方網站文檔http://www.w3.org獲取更多信息。

       XML在不同的語言裏解析方式都是一樣的,只不過實現的語法不同而已。基本的解析方式有兩種,一種叫SAX,另一種叫DOM。SAX是基於事件流的解析,DOM是基於XML文檔樹結構的解析。

        在做一般的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


下節開始,將爲大家介紹Java解析XML文件的四種經典方法,希望對大家有所幫助


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章