代码如下:
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
doc=builder.newDocument();
Element root = doc.createElement("root");
doc.appendChild(root);
System.out.println(doc.toString());
}catch(Exception _e){
}结果:null
郁闷!
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
doc=builder.newDocument();
Element root = doc.createElement("root");
doc.appendChild(root);
System.out.println(doc.toString());
}catch(Exception _e){
}结果:null
郁闷!
这个你看看书吧!
这是一个网上的例子
注意xml文件的格式,你自己也可定义 那就照着样子需要更改解析了
package xmlwriter;
import javax.xml.parsers.*;
import org.w3c.dom.*;public class xmldisplay {
public static void main(String args[]){
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("links.xml");
doc.normalize();
NodeList links =doc.getElementsByTagName("link");
for (int i=0;i<links.getLength();i++){
Element link=(Element) links.item(i);
System.out.print("Content: ");
System.out.println(link.getElementsByTagName("text").item(0).getFirstChild().getNodeValue());
System.out.print("URL: ");
System.out.println(link.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());
System.out.print("Author: ");
System.out.println(link.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
System.out.print("Date: ");
Element linkdate=(Element) link.getElementsByTagName("date").item(0);
String day=linkdate.getElementsByTagName("day").item(0).getFirstChild().getNodeValue();
String month=linkdate.getElementsByTagName("month").item(0).getFirstChild().getNodeValue();
String year=linkdate.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();
System.out.println(day+"-"+month+"-"+year);
System.out.print("Description: ");
System.out.println(link.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());
System.out.println();
}
}catch(Exception e){
e.printStackTrace();
}}
}
节点名称 同名节点在文档中索引序号.