一、理論準備 SAX採用事件驅動機制來解析XML文檔,每當SAX解析器發現文檔開始、元素開始、文本、元素結束、文檔結束等事件時,就會向外發送一次事件,而開發人員則可以通過編寫事件監聽器處理這些事件,以此來擷取XML文檔裡的資訊。 DOM標準簡單易用,但是它需要一次性地讀取整個XML文檔,而且在程式運行期間,整個DOM樹常駐記憶體,導致系統開銷過大。SAX解析方式佔用記憶體小,處理速度更快。 由於DOM一次性將整個XML文檔全部讀入記憶體,因此可以隨機訪問XML文檔的每個元素。SAX採用順序模式來依次讀取XML文檔,因此無法做到隨機訪問XML文檔的任意元素。 二、項目結構 image框住的是本執行個體需要的代碼。 三、執行個體實現 <?xml version="1.0" encoding="UTF-8"?><persons> <person id="1"> <name>Jack</name> <age>24</age> </person> <person id="2"> <name>Tom</name> <age>25</age> </person> <person id="3"> <name>Bob</name> <age>22</age> </person></persons> ps:不知道為啥,用xml格式發布就出問題,用java就不出問題~~憤怒 不知道咋回事Test類就是插不進去,顯示一半,氣死了。。直接看吧package xml; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; public class Test { static String URL_PATH = "http://localhost:8080/TestGet/person.xml"; public static InputStream getInputStream() throws IOException { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL(URL_PATH); if (url != null) { httpURLConnection = (HttpURLConnection) url.openConnection(); // 設定串連網路的逾時時間 httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true); // 設定本次http請求使用get方式請求 httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { // 從伺服器獲得一個輸入資料流 inputStream = httpURLConnection.getInputStream(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return inputStream; } public static void main(String[] args) throws IOException, Exception { // TODO Auto-generated method stub if(getInputStream()==null) { System.out.println("讀取失敗"); return ; } List<Person> person = SaxService.readXML(getInputStream()); System.out.println(person.size()); for(int i=0; i<person.size(); i++) System.out.println("id:"+person.get(i).getId()+"age:"+person.get(i).getAge() +"name:"+person.get(i).getName()); } } 結果如下: + View Code四、遺留問題 1.sax解析中Name和localName什麼區別,想到這個是因為一哥們用的localName和person判斷他表示結果對了,費解??? 2.endElement的if裡把person設定為null是為了防止重複觸發該事件,之後把currentTag設定為null是何意?莫非存在如下情況,費解啊。。。