1 packagecom.test;2
3 importjava.io.File;4 importjava.io.FileInputStream;5 importjava.util.ArrayList;6 importjava.util.List;7
8 importjavax.xml.parsers.SAXParser;9 importjavax.xml.parsers.SAXParserFactory;10
11 importorg.xml.sax.Attributes;12 importorg.xml.sax.SAXException;13 importorg.xml.sax.helpers.DefaultHandler;14
15 public classSaxXML {16
17 public static voidmain(String[] args) {18 File file = new File("e:/People.xml");19 try{20 SAXParserFactory spf =SAXParserFactory.newInstance();21 SAXParser parser =spf.newSAXParser();22 SaxHandler handler = new SaxHandler("People");23 parser.parse(newFileInputStream(file), handler);24
25 List peopleList =handler.getPeoples();26 for(People people : peopleList){27 System.out.println(people.getId()+"\t"+people.getName()+"\t"+people.getEnglishName()+"\t"+people.getAge());28 }29 } catch(Exception e) {30 //TODO Auto-generated catch block
31 e.printStackTrace();32 }33 }34
35 }36
37 class SaxHandler extendsDefaultHandler {38 private List peoples = null;39 privatePeople people;40 private String currentTag = null;41 private String currentValue = null;42 private String nodeName = null;43
44 public ListgetPeoples() {45 returnpeoples;46 }47
48 publicSaxHandler(String nodeName) {49 this.nodeName =nodeName;50 }51
52 @Override53 public void startDocument() throwsSAXException {54 //TODO 当读到一个开始标签的时候,会触发这个方法
55 super.startDocument();56
57 peoples = new ArrayList();58 }59
60 @Override61 public void endDocument() throwsSAXException {62 //TODO 自动生成的方法存根
63 super.endDocument();64 }65
66 @Override67 public voidstartElement(String uri, String localName, String name,68 Attributes attributes) throwsSAXException {69 //TODO 当遇到文档的开头的时候,调用这个方法
70 super.startElement(uri, localName, name, attributes);71
72 if(name.equals(nodeName)) {73 people = newPeople();74 }75 if (attributes != null && people != null) {76 for (int i = 0; i < attributes.getLength(); i++) {77 if(attributes.getQName(i).equals("id")){78 people.setId(attributes.getValue(i));79 }80 else if(attributes.getQName(i).equals("en")){81 people.setEnglishName(attributes.getValue(i));82 }83 }84 }85 currentTag =name;86 }87
88 @Override89 public void characters(char[] ch, int start, intlength)90 throwsSAXException {91 //TODO 这个方法用来处理在XML文件中读到的内容
92 super.characters(ch, start, length);93
94 if (currentTag != null && people != null) {95 currentValue = newString(ch, start, length);96 if (currentValue != null && !currentValue.trim().equals("") && !currentValue.trim().equals("\n")) {97 if(currentTag.equals("Name")){98 people.setName(currentValue);99 }100 else if(currentTag.equals("Age")){101 people.setAge(currentValue);102 }103 }104 }105 currentTag = null;106 currentValue = null;107 }108
109 @Override110 public voidendElement(String uri, String localName, String name)111 throwsSAXException {112 //TODO 在遇到结束标签的时候,调用这个方法
113 super.endElement(uri, localName, name);114
115 if(name.equals(nodeName)) {116 peoples.add(people);117 }118 }119
120 }