java读取XML文件,使用3wc.dom.*包

来源:互联网 发布:unitedstack 知乎 编辑:程序博客网 时间:2024/04/20 02:22
 

xml file  test.xml

<?xml version="1.0" encoding="utf-8" ?>
 <book>
 <person>
<empid>101</empid>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
<sal>12300</sal>
</person>
 <person>
<empid>102</empid>
<first>Bill</first>
<last>Gates</last>
<age>22</age>
<sal>12300</sal>
</person>
<person>
<empid>103</empid>
<first>Steve</first>
<last>Jobs</last>
<age>22</age>
<sal>12300</sal>
</person>
<person>
<empid>104</empid>
<first>joe</first>
<last>singh</last>
<age>25</age>
<sal>6300</sal>
</person>
</book>

 import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

public void read_xml(){
 try {
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
  Document doc = docBuilder.parse(new File("C:/test.xml"));
  Element root = doc.getDocumentElement();
  System.out.println("root ==> "+root.getNodeName());   //根节点名
  NodeList children = root.getChildNodes();           
  System.out.println("leng ==>  "+children.getLength());

  for(int i=1;i<children.getLength();i++)
  System.out.println("sub name :: "+children.item(i++).getNodeName());
  
  System.out.println("Grandchildren last");
  for (int i = 1; i < children.getLength(); i++)
  {
      Node peak = children.item(i);
      System.out.println("Grandchildren last");
      for (int j=1; j <peak.getChildNodes().getLength(); j++)
   {
   System.out.println("name :: "+(peak.getChildNodes().item(j++).getNodeName()));
   }
    
  }
  }
  catch(Exception e){}
  }
   public static void main(String args[]){
    ReadXml rx=new ReadXml();
    rx.read_xml();
   }