import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

public class DOMTest
{
   public static void main (String args[])
   {
	   //生成一个文件
      File docFile = new File("DOMTest.xml");
      Document doc = null;
      try
      {
		 //使用工厂方法产生DocumentBuilder
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         //解析文件
         doc = db.parse(docFile);
      }
      catch (Exception e)
      {
         System.out.print("Problem parsing the file.");
      }
      //得到根元素
      Element root = doc.getDocumentElement();
	    System.out.println("The root element is "+root.getNodeName());
	    //得到根元素的全部节点
	    NodeList children = root.getChildNodes();
	    System.out.println("There are "+children.getLength()+" nodes in this document.");
	    //从根元素开始递归的遍历各个节点
	    stepThrough(root);
   }
   //递归的遍历从start开始的各个节点
   private static void stepThrough (Node start)
   {
	  //取得该节点的值
	  System.out.println(start.getNodeName()+" = "+start.getNodeValue());
	  //如果是一个元素节点，则读其他的属性
	  if (start.getNodeType() == start.ELEMENT_NODE)
      {
		  //取得节点的全部属性
      	  NamedNodeMap startAttr = start.getAttributes();
      	  //访问每一个属性
          for (int i = 0; i < startAttr.getLength();i++)
          {
			  Node attr = startAttr.item(i);
			  //输出属性名和属性值
              System.out.println("  Attribute:  "+ attr.getNodeName()+" =  " +  attr.getNodeValue());
          }
       }
       //访问本节点完毕，继续递归的访问他的每一个字节点
	   for (Node child = start.getFirstChild();child != null;child = child.getNextSibling())
	   {
		  stepThrough(child);
	   }
	}
}
