DOM
将XML文档换成一个对象模型的集合(DOM树),应用程序通过对模型的操作完成对XML数据的操作
File xmlfile=new File("D:/MyEclipse 10/test/WebRoot/NewFile.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
try{
builder=factory.newDocumentBuilder();
}catch(ParserConfigurationException e){
e.printStackTrace();
}
org.w3c.dom.Document doc=null;
if(builder!=null){
try{
doc=builder.parse(xmlfile);
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
if(doc!=null){
NodeList nl=doc.getElementsByTagName("name");
System.out.println(nl.item(0).getFirstChild().getNodeValue());
}
SAX
按顺序访问
package tets;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLBySAX {
public static void main(String[] args) {
File xmlfile = new File("D:/MyEclipse 10/test/WebRoot/NewFile.xml");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser paser;
try {
paser = factory.newSAXParser();
paser.parse(xmlfile,new SAX());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SAX extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
@Override
public void endDocument() throws SAXException {
System.out.println("\n 文档读取结束");
}
@Override
public void startElement(String uri,String localName,String name,Attributes attributes) throws SAXException {
System.out.print("<" + name);
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
System.out.print(" " + attributes.getQName(i) + "=\""
+ attributes.getValue(i) + "\"");
}
}
System.out.print(">");
}
@Override
public void endElement(String uri,String name)
throws SAXException {
System.out.print("</" + name + ">");
}
@Override
public void characters(char[] ch,int start,int length)
throws SAXException {
System.out.print(new String(ch,start,length));
}
}
hibernate和spring框架都是用DOM4J读取xml配置文件的,另外还有一个Java组件 JDOM=DOM的修改文件+SAX的读取快速