複製程式碼如下:
包com.test;
導入java.io.File;
導入 java.io.FileInputStream;
導入java.util.ArrayList;
導入java.util.List;
導入 javax.xml.parsers.SAXParser;
導入 javax.xml.parsers.SAXParserFactory;
匯入 org.xml.sax.Attributes;
導入 org.xml.sax.SAXException;
導入 org.xml.sax.helpers.DefaultHandler;
公共類別 SaxXML {
公共靜態無效主(字串[] args){
文件 file = new File("e:/People.xml");
嘗試 {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser 解析器 = spf.newSAXParser();
SaxHandler 處理程序 = new SaxHandler("People");
parser.parse(new FileInputStream(file), handler);
List<People> peopleList = handler.getPeoples();
為(人民:人民名單){
System.out.println(people.getId()+"/t"+people.getName()+"/t"+people.getEnglishName()+"/t"+people.getAge());
}
} catch (異常 e) {
// TODO 自動產生的 catch 區塊
e.printStackTrace();
}
}
}
類別 SaxHandler 擴展 DefaultHandler {
私有清單 <People> peoples = null;
私人人士;
私有字串 currentTag = null;
私有字串當前值 = null;
私有字串節點名稱 = null;
公用清單 <People> getPeoples() {
回歸人民;
}
公共 SaxHandler(字串節點名稱) {
this.nodeName = 節點名稱;
}
@覆蓋
公有無效startDocument()拋出SAXException {
// TODO 當讀到一個開始標籤的時候,會觸發這個方法
super.startDocument();
peoples = new ArrayList<People>();
}
@覆蓋
公用無效endDocument()拋出SAXException {
// TODO 自動產生的方法存根
super.endDocument();
}
@覆蓋
公共無效startElement(字串uri,字串本地名稱,字串名稱,
屬性屬性)拋出 SAXException {
// TODO 當遇到文檔的參考的時候,呼叫這個方法
super.startElement(uri, localName, 名稱, 屬性);
if (name.equals(nodeName)) {
人=新人();
}
if (屬性!= null && 人們!= null) {
for (int i = 0; i < attribute.getLength(); i++) {
if(attributes.getQName(i).equals("id")){
people.setId(attributes.getValue(i));
}
否則 if(attributes.getQName(i).equals("en")){
people.setEnglishName(attributes.getValue(i));
}
}
}
目前標籤=名稱;
}
@覆蓋
公共無效字元(char [] ch,int開始,int長度)
拋出 SAXException {
// TODO 這個方法用來處理在 XML 檔案中讀取到的內容
super.characters(ch, 開始, 長度);
if (currentTag!= null && people!= null) {
currentValue = new String(ch, 開始, 長度);
if (currentValue != null && !currentValue.trim().equals("") && !currentValue.trim().equals("/n")) {
if(currentTag.equals("名稱")){
people.setName(currentValue);
}
否則 if(currentTag.equals("年齡")){
people.setAge(currentValue);
}
}
}
目前標籤=空;
當前值=空;
}
@覆蓋
公共無效endElement(字串uri,字串本地名稱,字串名稱)
拋出 SAXException {
// TODO 在遇到結束標籤的時候,呼叫這個方法
super.endElement(uri, localName, 名稱);
if (name.equals(nodeName)) {
peoples.add(people);
}
}
}