<?xml version="1.0" encoding="GB18030" ?>
<teacher>
<name note="95年调入海南大学">王小明</name>
<college>信息学院</college>
<telphone>6258113</telphone>
<notes>男,1955年生,博士,95年调入海南大学</notes>
</teacher>
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.SAXException;
public class SAXHandler extends HandlerBase {
private Map<String ,String> map = new HashMap<String,String>();
private String value="";
private String name="";
AttributeList attributest;
public void characters(char[] ch, int start, int length)
throws SAXException {
value = new String(ch, start, length);
}
@Override
public void startElement(String name, AttributeList attributes)
throws SAXException {
this.name = name;
this.attributest=attributes;
}
@Override
public void endElement(String name) throws SAXException {
if (name.equals(this.name)) {
map.put(this.name, this.value);
}
for (int i = 0; i < attributest.getLength(); i++) {
map.put(attributest.getName(i), attributest.getValue(i));
}
}
public String getValue(String name) {
return map.get(name)==null?"":map.get(name);
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
SAXHandler handler = new SAXHandler();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
String pathname = "teacher.xml";
parser.parse(new File(pathname), handler);
String name = "name";
System.out.println(handler.getValue(name));
name="note";
System.out.println(handler.getValue(name));
}
}
用HandlerBase解析标签及其元素
最新推荐文章于 2024-01-19 14:30:40 发布