深入淺出如何解析xml檔案 下篇
阿新 • • 發佈:2019-02-12
import java.util.ArrayList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * 功能描述:採用sax方式解析XML<br> * * @author 丁國華 * */ public class SaxParseXml extends DefaultHandler{ //存放遍歷集合 private List<Student> list; //構建Student物件 private Student student; //用來存放每次遍歷後的元素名稱(節點名稱) private String tagName; public List<Student> getList() { return list; } public void setList(List<Student> list) { this.list = list; } public Student getStudent() { return student; } public void setStudent(Student student) { this .student = student; } public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } //只調用一次 初始化list集合 public void startDocument() throws SAXException { list=new ArrayList<Student>(); } //呼叫多次 開始解析 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("student")){ student=new Student(); //獲取student節點上的id屬性值 student.setId(Integer.parseInt(attributes.getValue(0))); //獲取student節點上的group屬性值 student.setGroup(Integer.parseInt(attributes.getValue(1))); } this.tagName=qName; } //呼叫多次 public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equals("student")){ this.list.add(this.student); } this.tagName=null; } //只調用一次 public void endDocument() throws SAXException { } //呼叫多次 public void characters(char[] ch, int start, int length) throws SAXException { if(this.tagName!=null){ String date=new String(ch,start,length); if(this.tagName.equals("name")){ this.student.setName(date); } else if(this.tagName.equals("sex")){ this.student.setSex(date); } else if(this.tagName.equals("age")){ this.student.setAge(Integer.parseInt(date)); } else if(this.tagName.equals("email")){ this.student.setEmail(date); } else if(this.tagName.equals("birthday")){ this.student.setBirthday(date); } else if(this.tagName.equals("memo")){ this.student.setMemo(date); } } } }