Java DOM 的 API:
1.解析器工厂类:DocumentBuilderFactory
创建的方法:DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
2.解析器:DocumentBuilder
创建方法:通过解析器工厂类来获得 DocumentBuilder db = dbf.newDocumentBuilder();
3.文档树模型Document
创建方法:a.通过xml文档 Document doc = db.parse("bean.xml");
b.将需要解析的xml文档转化为输入流 InputStream is = new FileInputStream("bean.xml"); Document doc = db.parse(is);
Document对象代表了一个XML文档的模型树,所有的其他Node都以一定的顺序包含在Document对象之内,排列成一个树状结构,以后对XML文档的所有操作都与解析器无关,
直接在这个Document对象上进行操作即可;
package util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XmlUtil {
public static void main(String[] args){
try {
//得到DOM解析器的工厂实例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//从DOM工厂中获得DOM解析器
DocumentBuilder db = dbf.newDocumentBuilder();
/*String xmlFile = "web-context.xml";
File file = new File(xmlFile);
Document doc = db.parse(file);*/
/*String xmlFile = "web-contextt.xml";
FileInputStream is = new FileInputStream(xmlFile);
Document doc = db.parse(is);*/
//把要解析的xml文档读入DOM解析器
String xmlFile = "web-context.xml";
Document doc = db.parse(xmlFile);
Element root = doc.getDocumentElement();
System.out.println(root.getTagName());
NodeList nodes = doc.getElementsByTagName("bean");
int length = nodes.getLength();
for(int i=0;i<length;i++){
Element el = (Element)nodes.item(i);
String name = el.getAttribute("name");
name = name.replace("/", "");
System.out.println(name);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="GB2312" ?> <beans> <description>定义web层的资源</description> <bean name="/unitPrice.do"> <property name="commandName"> <value>form</value> </property> </bean> <bean name="/assetCounterAsset.do"> <property name="commandName"> <value>form</value> </property> </bean> <bean name="/projectByNode.do"> <description>下拉选择框的公共Controller</description> <property name="viewName"> <value>pubView</value> </property> </bean> <bean name="/assetParamValue.do"> <property name="commandName"> <value>form</value> </property> </bean> </beans>