<?xml version="1.0" encoding="UTF-8"?> <students> <student id="1001"> <stuno>1001</stuno> <name>張三</name> <sex>男</sex> <grade>Java一班</grade> </student> <student id="1002"> <stuno>1002</stuno> <name>李四</name> <sex>女</sex> <grade>Java二班</grade> </student> <student id="1003"> <stuno>1003</stuno> <name>小二</name> <sex>男</sex> <grade>Java三班</grade> </student> <student id="1004"> <stuno>1004</stuno> <name>小蠟</name> <sex>女</sex> <grade>Java四班</grade> </student> </students>
1 package xmlpulldemo; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 6 import org.xmlpull.v1.XmlPullParser; 7 import org.xmlpull.v1.XmlPullParserException; 8 import org.xmlpull.v1.XmlPullParserFactory; 9 10 public class XmlPullDemo { 11 12 public static void main(String[] args) throws XmlPullParserException, IOException { 13 14 // 創建一個解析工廠 15 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 16 // 由工廠創建一個解析器對象 17 XmlPullParser parser = factory.newPullParser(); 18 // 打開xml文檔對應的輸入流,填寫xml文檔的路徑 19 parser.setInput(new FileInputStream("src/xmlwendang/student.xml"), "UTF-8"); 20 // 獲得事件類型 21 int eventType = parser.getEventType(); 22 System.out.println(eventType == XmlPullParser.START_DOCUMENT); 23 do { 24 switch (eventType) { 25 case XmlPullParser.START_DOCUMENT: 26 System.out.println("讀取開始,開始文檔!"); 27 break; 28 case XmlPullParser.START_TAG: 29 String tagName = parser.getName(); 30 if (tagName.equals("student")) { 31 System.out.println("讀取進度-開始標簽:" + parser.getName() + ":" + parser.getAttributeName(0) + ":" 32 + parser.getAttributeValue(0)); 33 } else if (tagName.equals("stuno")) { 34 System.out.println("讀取進度-學號:" + parser.nextText()); 35 } else if (tagName.equals("name")) { 36 System.out.println("讀取進度-姓名:" + parser.nextText()); 37 } else if (tagName.equals("sex")) { 38 System.out.println("讀取進度-性別:" + parser.nextText()); 39 } else if (tagName.equals("grade")) { 40 System.out.println("讀取進度-班級:" + parser.nextText()); 41 } else if (tagName.equals("students")) { 42 System.out.println("讀取開始-開始根目錄:" + parser.getName()); 43 } 44 break; 45 case XmlPullParser.END_TAG: 46 if (parser.getName().equals("student")) { 47 System.out.println("讀取進度-結束標簽:" + parser.getName()); 48 } else if (parser.getName().equals("students")) { 49 System.out.println("讀取完成-結束根目錄:" + parser.getName()); 50 } 51 break; 52 } 53 // 讀取下一個節點 54 eventType = parser.next(); 55 } while (eventType != XmlPullParser.END_DOCUMENT); 56 System.out.println("讀取完成,文檔結束!"); 57 } 58 59 }
結果:
1 true 2 讀取開始,開始文檔! 3 讀取開始-開始根目錄:students 4 讀取進度-開始標簽:student:id:1001 5 讀取進度-學號:1001 6 讀取進度-姓名:張三 7 讀取進度-性別:男 8 讀取進度-班級:Java一班 9 讀取進度-結束標簽:student 10 讀取進度-開始標簽:student:id:1002 11 讀取進度-學號:1002 12 讀取進度-姓名:李四 13 讀取進度-性別:女 14 讀取進度-班級:Java二班 15 讀取進度-結束標簽:student 16 讀取進度-開始標簽:student:id:1003 17 讀取進度-學號:1003 18 讀取進度-姓名:小二 19 讀取進度-性別:男 20 讀取進度-班級:Java三班 21 讀取進度-結束標簽:student 22 讀取進度-開始標簽:student:id:1004 23 讀取進度-學號:1004 24 讀取進度-姓名:小蠟 25 讀取進度-性別:女 26 讀取進度-班級:Java四班 27 讀取進度-結束標簽:student 28 讀取完成-結束根目錄:students 29 讀取完成,文檔結束!