昨天用了DOM解析XML文件并原样输出,今天上网看见了还有SAX解析,两者的区别是DOM解析是按节点解析,SAX解析是按行解析,废话不多说,上代码吧
public class ParseXML {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse("src/hello.xml", new MyHandle());
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandle extends DefaultHandler {
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.print("<"+qName);
int length=attributes.getLength();
for (int i = 0; i < length; i++) {
System.out.print(" "+attributes.getQName(i)+"=\""+attributes.getValue(i)+"\"");
}
System.out.print(">");
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.print("</"+qName+">");
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String value=new String(ch, start, length);
System.out.print(value);
}
}
<?xml version="1.0" encoding="utf-8"?>
<students>
<student id="001">
<name>张三</name>
<age>23</age>
<address>USA</address>
</student>
<student id="002">
<name>李四</name>
<age>24</age>
<address>USA</address>
</student>
<student id="003">
<name>王五</name>
<age>25</age>
<address>USA</address>
</student>
</students>
不得不说SAX解析比DOM解析简单多了,昨天用DOM解析,头都被节点弄昏了,今天用SAX解析还是很快就写完了,还是很开心啊,技多不压身,哈哈,睡觉