//stu.xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <exam> <student> <name>张三</name> <location>西安</location> <grade>98</grade> </student> <student> <name>李四</name> <location>临潼</location> <grade>59</grade> </student> </exam>
sax_study.java
package com.SAX; import java.io.IOException; import java.util.ArrayList; 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.XMLReader; import org.xml.sax.helpers.DefaultHandler; import com.student.Student; public class sax_study { public static void main(String[]args) throws ParserConfigurationException,SAXException,IOException { SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser sp=factory.newSAXParser(); XMLReader reader=sp.getXMLReader(); BeanListHandler blh= new BeanListHandler(); reader.setContentHandler(blh); reader.parse("src/stu.xml"); ArrayList al=blh.getStudents(); for(int j=0;j<al.size();++j) { Student stu=(Student) al.get(j); System.out.println(stu.getName()+"---"+stu.getLocation()+"---"+stu.getGrade()); } } } class BeanListHandler extends DefaultHandler { ArrayList list=new ArrayList(); String current_tag=null; Student stu=null; public ArrayList getStudents() { return list; } @Override public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException { if("student".equals(qName)) //避免空指针异常,所以把字符串变量放在后面 { current_tag="student"; stu=new Student(); } else if("name".equals(qName)) { current_tag="name"; } else if("location".equals(qName)) { current_tag="location"; } else if("grade".equals(qName)) { current_tag="grade"; } } @Override public void characters(char[] ch,int start,int length) throws SAXException { if("location".equals(current_tag ) ) { stu.setLocation(new String(ch,start,length)); } else if("grade".equals(current_tag)) { stu.setGrade(Integer.parseInt(new String(ch,length))); } else if("name".equals(current_tag)) { stu.setName(new String(ch,length)); } } @Override public void endElement(String uri,String qName) throws SAXException { if("student".equals(qName)) { list.add(stu); stu=null; } current_tag=null; //这句话千万不可省略,省略会报空指针异常, //因为遇到结束标签时,stu被置为null,然后遇到空白文本,stu调用set方法,报错 } }
Student.java
package com.student; public class Student { private String name; private String location; private int grade; public Student(String na,String lo,int gr) { name=na; location=lo; grade=gr; } public Student() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } }这种解析方式,在实际开发过程中比较常用应当掌握。 原文链接:https://www.f2er.com/xml/294883.html