中科院云平台架构师,专注于数字化、智能化,技术方向:云、Linux内核、AI、MES/ERP/CRM/OA、物联网、传感器、大数据、ML、微服务。
分类: Java
2013-04-26 17:49:03
import java.io.File;
import java.io.FileReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class Saxxml extends HandlerBase {
private String currentElement = null;
private String currentValue = null;
/**
* @param args
*/
public static void main(String[] args) {
try {
(new Saxxml()).run("c:\\member.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
public void run(String filename) throws Exception {
File file = new File(filename);
FileReader reader = new FileReader(file);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
Saxxml handler = new Saxxml();
sp.parse(new InputSource(reader), handler);
}
public void startDocument() throws SAXException {
System.out.println("starting parse XML file....");
}
public void startElement(String tag, AttributeList attrs) throws SAXException {
// currentElement = tag;
System.out.println(tag);
}
public void characters(char[] ch, int start, int length) throws SAXException {
// currentValue = new String(ch, start, length);
System.out.println(new String(ch, start, length));
}
public void endElement(String name) throws SAXException {
// if (currentElement.equals(name)) {
// table.put(currentElement, currentValue);
// }
}
public void endDocument() throws SAXException {
System.out.println("end parse XML file!");
}
}
AttributeList和HandlerBase在V1.6已经不推荐了。
HandlerBase和DefaultHandler很类似,可以替换。