java 读取xml文件

来源:互联网 发布:怎样分析销售数据 编辑:程序博客网 时间:2024/05/17 20:32

前题条件:dom4j-1.6.jar;jdom.jar

步骤1:创建基类

import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
/**
 * @author jy
 *  method 读取xml文件
 *  参数 xml文件路径及名称 , xml中需要循环取出节点的路径
 *  返回 节点数组(包括子节点)
 */

public class ReadXML {
 private String filepath="";
 private String loopNodePath="";
 
 public ReadXML(String filepath,String loopNodePath)
 {
  this.filepath=filepath;
  this.loopNodePath=loopNodePath;
 }
 public List init()
 { 
  SAXBuilder sb = new SAXBuilder();
      List nodeList=null;
   try {
      Document doc = sb.build(Thread.currentThread().getContextClassLoader().getResourceAsStream(this.filepath));
      Element rootElt = doc.getRootElement();
      nodeList = XPath.selectNodes(rootElt, this.loopNodePath); //因为要循环这个,所以不读到底层
         } catch (JDOMException e) {
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace();
     }
     return nodeList;
 }
}

 

步骤二:调用基类

package com.readXML;
import java.util.Iterator;
import java.util.List;
import org.jdom.Element;

public class ExampleReadXML {
 public static void main(String[] args) {
  String filepath="animal.xml";          //src目录下xml文件路径及名称
  String loopNodePath="//group/animal";  //需要循环取出的父节点名称
  
  ReadXML readxml=new ReadXML(filepath,loopNodePath);
  List nodelist=readxml.init();
   for(Iterator iter = nodelist.iterator();iter.hasNext();)
     {
    //循环取出父节点下的子节点
       Element titleElt = (Element)iter.next();
       System.out.println(titleElt.getChildText("animalGuid"));
       System.out.println(titleElt.getChildText("farmGuid"));
       System.out.println(titleElt.getChildText("farmName"));
       System.out.println(titleElt.getChildText("animalcode"));
       System.out.println(titleElt.getChildText("animalVariety"));
     }

 }

}