studentInfo
<?xml version=
<student>
<person age=
<name>崔衛兵</name>
<college>PC學院</college>
<telephone>
<notes>男
</person>
<person>
<name>cwb</name>
<college leader=
認的為leader
<telephone>
<notes>男
</person>
<person age=
<name>xxxxx</name>
<college leader=
<telephone>
<notes>注視中
</person>
</student>
SAXHandler
package saxExample;
import java
import org
import org
/**
* 繼承DefaultHandler類
* @author cuiweibing
* @since
*/
public class SAXHandler
extends DefaultHandler {
//存放所有的節點(這裡的節點等於原來的節點+編號)以及它所對應的值
private HashMap<String
//目前的節點
private String currentElement = null;
//目前節點所對應的值
private String currentValue = null;
//用於節點編號(具體到person)
private static int i=
public HashMap getHashMap() {
return hashMap;
}
public void characters(char[] ch
//取出目前節點對應的值
currentValue = new String(ch
}
public void startElement(String uri
Attributes attr) throws SAXException {
if(qName
//currentElement=
}else if (qName
i++;
//currentElement=
String age=attr
if(age!=null){
hashMap
}else{
hashMap
}
}else if (qName
currentElement= qName;
String leader=attr
if(leader!=null){
hashMap
}else{
hashMap
}
}else{
currentElement= qName;
}
}
public void endElement(String uri
if (qName
// hashMap
}else if (qName
}else{
currentElement+=i;
hashMap
}
}
}
TestSAXHandler
package saxExample;
import java
import java
import javax
import javax
/**
* 解析主類
* @author cuiweibing
* @since
*/
public class TestSAXHandler {
public TestSAXHandler() {
}
public static void main(String[] args) {
try{
//初始化與解析
SAXHandler handler = new SAXHandler();
SAXParserFactory saxparserfactory = SAXParserFactory
SAXParser saxparser = saxparserfactory
saxparser
//解析完後獲取解析信息
HashMap hashMap = handler
System
for(int i=
int j=i/
System
System
System
System
System
System
}
}catch(Exception ex){
ex
}
}
}
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19670.html