-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSAXPersonService.java
More file actions
executable file
·94 lines (75 loc) · 2.27 KB
/
Copy pathSAXPersonService.java
File metadata and controls
executable file
·94 lines (75 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class SAXPersonService {
public static void main(String[] args) throws Exception {
SAXPersonService sax = new SAXPersonService();
FileInputStream input = new FileInputStream("D://my.xml");
System.out.println(sax.getPerson(input));
}
public List<PersonBean> getPerson(InputStream inStream) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();//
PersonHanlder hanlder = new PersonHanlder();//
parser.parse(inStream, hanlder);
return hanlder.getPersons();
}
private class PersonHanlder extends DefaultHandler {
private List<PersonBean> persons;
PersonBean person = null;
private String tag = null;
public List<PersonBean> getPersons() {
return persons;
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
persons = new ArrayList<PersonBean>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if ("person".equals(localName)) {
person = new PersonBean();
person.setId(new Integer(attributes.getValue(0)));
// �õ���һ������ id
}
tag = localName;// tag==person
}
@Override
public void characters(char[] ch, int start, int length)//
throws SAXException {
// TODO Auto-generated method stub
/*
* String data = new String(ch, start, length); if(c==stu){
* c.add(data) }
*/
if (tag != null) {
String data = new String(ch, start, length);//
if ("name".equals(tag)) {
person.setName(data);
} else if ("age".equals(tag)) {
person.setAge(new Short(data));
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if ("person".equals(localName)) {
persons.add(person);
person = null;
}
tag = null;
}
}
}