复代码代码如下:
패키지 com.test;
java.io.파일 가져오기;
import java.io.FileInputStream;
import java.util.ArrayList;
java.util.List 가져오기;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
org.xml.sax.Attributes 가져오기;
import org.xml.sax.SAXException;
org.xml.sax.helpers.DefaultHandler 가져오기;
공개 클래스 SaxXML {
공개 정적 무효 메인(String[] args) {
파일 file = new File("e:/People.xml");
노력하다 {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser 파서 = spf.newSAXParser();
SaxHandler 핸들러 = new SaxHandler("사람");
parser.parse(new FileInputStream(파일), 핸들러);
List<People> peopleList = handler.getPeoples();
for(사람 사람 : peopleList){
System.out.println(people.getId()+"/t"+people.getName()+"/t"+people.getEnglishName()+"/t"+people.getAge());
}
} 잡기(예외 e) {
// TODO 자동 생성된 캐치 블록
e.printStackTrace();
}
}
}
클래스 SaxHandler는 DefaultHandler를 확장합니다.
개인 목록<People> 사람들 = null;
개인 사람들;
개인 문자열 currentTag = null;
개인 문자열 currentValue = null;
개인 문자열 nodeName = null;
공개 목록<People> getPeoples() {
귀환 사람들;
}
공공 SaxHandler(문자열 nodeName) {
this.nodeName = 노드이름;
}
@보수
public void startDocument()에서 SAXException이 발생합니다.
// TODO 当读到一个开始标签的时候,会触发这个방법
super.startDocument();
peoples = new ArrayList<People>();
}
@보수
public void endDocument()에서 SAXException이 발생합니다.
// TODO 자동생성방법存根
super.endDocument();
}
@보수
public void startElement(String uri, String localName, String name,
속성 속성)은 SAXException을 발생시킵니다.
// TODO 当遇到文档的开头的时候,调用这个방법
super.startElement(uri, localName, 이름, 속성);
if (name.equals(nodeName)) {
사람 = 새로운 사람();
}
if (속성 != null && people != null) {
for (int i = 0; i < attribute.getLength(); i++) {
if(attributes.getQName(i).equals("id")){
people.setId(attributes.getValue(i));
}
else if(attributes.getQName(i).equals("en")){
people.setEnglishName(attributes.getValue(i));
}
}
}
현재태그 = 이름;
}
@보수
공개 무효 문자(char[] ch, int start, int length)
SAXException 발생 {
// TODO 这个방법을 사용하여 XML文件中读到的内容
super.characters(ch, 시작, 길이);
if (currentTag != null && people != null) {
currentValue = new String(ch, start, length);
if (currentValue != null && !currentValue.trim().equals("") && !currentValue.trim().equals("/n")) {
if(currentTag.equals("이름")){
people.setName(현재값);
}
else if(currentTag.equals("나이")){
people.setAge(현재값);
}
}
}
현재태그 = null;
현재값 = null;
}
@보수
public void endElement(String uri, String localName, String name)
SAXException 발생 {
// TODO 在遇到结束标签的时候,调用这个방법
super.endElement(uri, localName, 이름);
if (name.equals(nodeName)) {
people.add(사람);
}
}
}