ReadXML_JDK .java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class ReadXML_JDK {
public ReadXML_JDK() throws ParserConfigurationException, SAXException, IOException{
SAXParserFactory saxfac = SAXParserFactory.newInstance();
SAXParser saxparser = saxfac.newSAXParser();
//InputStream is = new FileInputStream(System.getProperty("user.dir") + File.separator + "test.xml");//读取当前目录下的文档
InputStream is = new FileInputStream( "D:\桌面\test.xml");
saxparser.parse(is,new MySAXHandler());
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
new ReadXML_JDK();
}
}
MySAXHandler .java
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MySAXHandler extends DefaultHandler {
boolean hasAttribute=false;
Attributes attributes=null;
private String currentTag;//当前节点的名称
public void startdocument() throws SAXException {
System.out.println("文档开始打印了");
}
public void enddocument() throws SAXException {
System.out.println("文档打印结束了");
}
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if(qName.equals("生物")){
return;
}
if(qName.equals("哺乳动物")){
// System.out.println(attributes.getQName(0)+" "+attributes.getValue(0));
}
if(attributes.getLength()>0){
this.attributes=attributes;
this.hasAttribute=true;
}
currentTag = qName;//当前节点名称
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(hasAttribute&&(attributes!=null)){
for(int i=0;i 0) {//标签中的内容
if(currentTag.equals("哺乳动物"))
System.out.println(currentTag+ " "+ contents);
}
}
}
结果



