java學習筆記——使用DOM解析XML和使用SAX解析XML

來源:互聯網
上載者:User

科普:

1) DOM

     DOM
是用與平台和語言無關的方式表示 XML 文檔的官方 W3C 標準。DOM 是以階層組織的節點或資訊片斷的集合。這個階層允許開發人員在樹中尋找特定資訊。分析該結構通常需要載入整個文檔和構造階層,然後才能做任何工作。由於它是基於資訊層次的,因而 DOM 被認為是基於樹或基於對象的。DOM 以及廣義的基於樹的處理具有幾個優點。首先,由於樹在記憶體中是持久的,因此可以修改它以便應用程式能對資料和結構作出更改。它還可以在任何時候在樹中上下導航,而不是像
SAX 那樣是一次性的處理。DOM 使用起來也要簡單得多。 

    
另一方面,對於特別大的文檔,解析和載入整個文檔可能很慢且很耗資源,因此使用其他手段來處理這樣的資料會更好。這些基於事件的模型,比如 SAX。 

 

2) SAX 

     這種處理的優點非常類似於流媒體的優點。分析能夠立即開始,而不是等待所有的資料被處理。而且,由於應用程式只是在讀取資料時檢查資料,因此不需要將資料存放區在記憶體中。這對於大型文檔來說是個巨大的優點。事實上,應用程式甚至不必解析整個文檔;它可以在某個條件得到滿足時停止解析。一般來說,SAX還比它的替代者 DOM 快許多。

優點與缺點

DOM:

      
解析器讀入整個文檔,然後構建一個駐留記憶體的樹結構,然後代碼就可以使用 DOM 介面來操作這個樹結構。

      
優點:整個文檔樹在記憶體中,便於操作;支援刪除、修改、重新排列等多種功能;

      
缺點:將整個文檔調入記憶體(包括無用的節點),浪費時間和空間;

      
使用場合:一旦解析了文檔還需多次訪問這些資料;硬體資源充足(記憶體、CPU)

 

SAX:

       事件驅動。當解析器發現元素開始、元素結束、文本、文檔的開始或結束等時,發送事件,程式員編寫響應這些事件的代碼,儲存資料。

      
優點:不用事先調入整個文檔,佔用資源少

      
缺點:不是持久的;事件過後,若沒儲存資料,那麼資料就丟了;無狀態性;從事件中只能得到文本,但不知該文本屬於哪個元素;

      
使用場合:只需XML文檔的少量內容,很少回頭訪問;一次性讀取;機器記憶體少;

      
注意:SAX 解析器不建立任何對象。

使用DOM解析XML:

package com.accp.xml;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import com.accp.entity.Pet;public class DomParseXML {public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {String fileURL="pet.xml";List<Pet> petList = parseXML(fileURL);for (Pet pet : petList) {System.out.println(pet);}}public static List<Pet> parseXML(String fileURL) throws SAXException,IOException, ParserConfigurationException {List<Pet> petList = new ArrayList<Pet>();// 獲得XML DOM解析器工廠執行個體DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();// 通過解析器工廠獲得xml解析器對象DocumentBuilder db = dbf.newDocumentBuilder();// 獲得文檔對象Document doc = db.parse(fileURL);// 獲得dog節點下的所有子節點NodeList nodeList = doc.getElementsByTagName("dog");for (int i = 0; i < nodeList.getLength(); i++) {Node node = nodeList.item(i);// 如果是元素節點if (node.getNodeType() == Node.ELEMENT_NODE) {Pet pet = new Pet();Element dog = (Element) node;// 獲得當前節點的id屬性String id = dog.getAttribute("id");//給id屬性賦值pet.setId(Integer.parseInt(id));// 獲得當前節點下的所有子節點for (Node childNode = dog.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) {if (childNode.getNodeType() == Node.ELEMENT_NODE) {// 獲得節點名稱String name = childNode.getNodeName();// 獲得節點值String value = childNode.getFirstChild().getNodeValue();//給各個屬性賦值if("name".equals(name)){pet.setName(value);}else if("health".equals(name)){pet.setHealth(Integer.parseInt(value));}else if("love".equals(name)){pet.setLove(Integer.parseInt(value));}else if("strain".equals(name)){pet.setStrain(value);}}}petList.add(pet); //添加對象到集合}}return petList;}}

使用SAX解析XML:

package com.accp.xml;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import com.accp.entity.Pet;public class SaxParseXML extends DefaultHandler {private List<Pet> list = null;private Pet pet = null; private String preTagName = null;//獲得pet集合的方法public List<Pet> getPet(String fileURL) throws ParserConfigurationException, SAXException, IOException{//獲得sax解析器工廠SAXParserFactory factory=SAXParserFactory.newInstance();//從工廠建立sax解析器SAXParser parser=factory.newSAXParser();//將指定的 資源標識符 (URI) 描述的內容解析為 XMLparser.parse(fileURL, this);//返回pet集合return this.list; }//接收元素節點開始所調用的方法@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {//輸出節點名稱System.out.println(qName);if("dog".equals(qName)){//建立一個pet對象pet=new Pet();//得到當前節點的id屬性值String id=attributes.getValue("id");//給id屬性賦值pet.setId(Integer.parseInt(id));}//儲存當前節點名稱preTagName=qName;}//接收元素節點結束所調用的方法@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {if("dog".equals(qName)){//將建立的pet對象添加到集合list.add(pet);//添加完後賦空值,避免重複添加pet=null;}//將儲存的節點名稱賦空值preTagName=null;}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {//給pet的各個屬性賦值if("name".equals(preTagName)){String content=new String(ch,start,length);pet.setName(content);}else if("health".equals(preTagName)){String content=new String(ch,start,length);pet.setHealth(Integer.parseInt(content));}else if("love".equals(preTagName)){String content=new String(ch,start,length);pet.setLove(Integer.parseInt(content));}else if("strain".equals(preTagName)){String content=new String(ch,start,length);pet.setStrain(content);}}// 開始文檔解析所調用的方法@Overridepublic void startDocument() throws SAXException {System.out.println("開始解析文檔");list = new ArrayList<Pet>();}// 文檔解析結束所調用的方法@Overridepublic void endDocument() throws SAXException {System.out.println("解析文檔結束");}}

測試類別:

public class SaxParseXMLTest {public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {SaxParseXML saxParseXML=new SaxParseXML();String fileURL="pet.xml";List<Pet> list=saxParseXML.getPet(fileURL);for (Pet pet : list) {System.out.println(pet);}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.