public static void main (String[] args) throws Exception{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("config.xml");
//Element rootElement = doc.getDocumentElement();这句话如果不写我的程序运行没有问题,能够解析XML文件
NodeList lists=doc.getElementsByTagName("action");
for (int i = 0; i<lists.getLength(); i++){
Node node=lists.item(i);
Element ele=(Element)node;
String path=ele.getAttribute("path");
System.out.println (path);
NodeList lists2=ele.getElementsByTagName("forward");
for (int j = 0; j<lists2.getLength(); j++){
Node node2= lists2.item(j);
Element ele2=(Element)node2;
System.out.println (ele2.getAttribute("name"));
System.out.println (ele2.getFirstChild().getNodeValue());
}
}
System.out.println(lists.getLength());
}
我想问一下这句话Element rootElement = doc.getDocumentElement();是不是必须要加的,我发现不加程序也能运行,请问什么情况下必须加,什么情况下可以不加?
我想问一下这句话Element rootElement = doc.getDocumentElement();是不是必须要加的,我发现不加程序也能运行,请问什么情况下必须加,什么情况下可以不加?
是可以不用加的
[code="java"]Element rootElement = document.getDocumentElement();
NodeList list = rootElement.getChildNodes();[/code]
但是当你要获取这个元素下有多少个子元素就要用这个了.
Element rootElement = doc.getDocumentElement();
//这条语句是用来得到根元素
比如下面这个xml文件,这条语句就是用来得到web-app元素
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
DWR (Direct Web Remoting)
A Simple Demo DWR