DOM4j SAXReader 读取XML文件

SAXReader主要用于解析XML文件,是当前比较流行的xml解决方案.
使用SAXReader需要下载dom4j的jar包(dom4j-1.6.1.jar)
Document document=new SAXReader.reader(“xml文路径/文件名xxx.xml”);//得到Document对象

Element root = document.getRootElement()//获得根节点

List<Element> nodes = root.elements("student");

String id = node.elementText("id")

Iterator iterator=root.elementIterator(); //从根节点遍历子节点Iterator iterator=Element.elementIterator(); //再从子节点在遍历其子节点对节点访问其属性用:Attribute leaderAttr =Element. attribute(“xxx”);对节点访问其某个属性leaderAttr的名称:leaderAttr.getName();对节点访问其某个属性leaderAttr的值:leaderAttr.getValue()对节点访问其名称:Element.getName();对节点访问其文本:Element. getText();

String xmlAddress = "./aaa.xml";
SAXReader reader = new SAXReader();
File xmlFile = new File(xmlAddress);
Document document = reader.read(xmlFile);

InputStream in = this.getClass().getResourceAsStream("photo.xml")

方法getResourceAsStream()是一个标准方法,用来打开一个外部输入文件。文件的位置取决于类加载器,而标准的类加载器从classpath开始搜索 如:c:/temp/mytest/Test.class   package   mytest;     public   class   Test{...}         Test.class.getResourceAsStream(str);         str="/db.properties"   则   db.properties   放在   c:/temp下     str="db.properties"   则   db.properties   放在c:/temp/mytest下 JAVA里面对于类进行调用配置资源的文件数据,以this.getClass().getResourceAsStream()来读取比较合适。
Document document = reader.read(in);
这里用FILE方式读取,其实用URL是一样的------------------------------------------用dom4j就要用XPath,索引节点非常方便这里的XPathExpression就是类似"/root/element/element"的字符串具体表达式的应用去看下XPath教程就行,入手很容易//返回符合表达式的节点LISTList list = document.selectNodes(XPathExpression);//返回符合表达式的一个节点Node node = document.selectSingleNode(XPathExpression);

SAXReader reader = new SAXReader();  
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);  
    /* 在读取文件时,去掉dtd的验证,可以缩短运行时间  */  
    reader.setEncoding("UTF-8");  
    Document document = reader.read(new File(文件路径)); 

例子:
package com.dc.framework.taglib;   
import java.io.FileInputStream;   
import java.io.FileNotFoundException;   
import java.util.HashMap;   
import java.util.Iterator;   
import java.util.List;   
import java.util.Map;   
import javax.servlet.ServletRequest;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.jsp.JspTagException;   
import javax.servlet.jsp.tagext.TagSupport;   
import org.apache.commons.lang.StringUtils;   
import org.dom4j.Document;   
import org.dom4j.DocumentException;   
import org.dom4j.Element;   
import org.dom4j.io.SAXReader;   
   
 
//自定义标签处理类   
public class ReadUploadFile {   
    // 配置文件的路径   
    static String uploadCfgFile = "WEB-INF/conf/uploadfile.xml";   
    //文档对象实体   
    Document uploadDocument = null;   
    //结果存储体   
    Map uploadMap = new HashMap();   
       
/** 
  * @param request 
  * @return 
  * 获取配置文件绝对路径 
  */ 
private String getuploadCfgFile(ServletRequest request) {   
      return ((HttpServletRequest) request).getSession().getServletContext().getRealPath(uploadCfgFile);   
}   
   
/** 
  * @param request 
  * @return 
  * 初始化配置文件 
  */ 
private Document inituploadCfgDocument(ServletRequest request) {   
      SAXReader saxReader = new SAXReader();   
      try {   
          //得到指定文件以流的形式对文件进行序列化   
          FileInputStream fis = new FileInputStream(getuploadCfgFile(request));   
          uploadDocument = saxReader.read(fis);   
      }   
      catch (DocumentException e) {   
          e.printStackTrace();   
      }   
      catch(FileNotFoundException fnfe){   
          fnfe.printStackTrace();   
      }   
      return uploadDocument;   
}   
   
/** 
  * 获取配置文件 
  * 
  * @param request 
  * @return 
  */ 
private Document getuploadCfgDocument(ServletRequest request) {   
      if (this.uploadDocument == null) {   
          this.uploadDocument = inituploadCfgDocument(request);   
      }   
      return this.uploadDocument;   
}   
 
/** 
  * @param request 
  * @return 
  * 获取某个指定preparents的配置属性 
  */ 
public Map getuploadMap(ServletRequest request) {   
    //xml中的访问路径,说明欲处理XML文件的根元素是fileaction-configuration   
    String xPath = "//fileaction-configuration/preparents";   
    //获取按照指定搜索路径得到的元素列表,这里指获取所有的fileaction-configuration下的preparents元素   
    List result = getuploadCfgDocument(request).selectNodes(xPath);   
    //属性和指定子元素的存储体   
    Map uploadMap = new HashMap();   
    //遍历所得元素   
    Iterator iter = result.iterator();   
    while (iter.hasNext()) {     
        //获得具体的preparents元素   
        Element preparents = (Element) iter.next();   
        // 取得preparents元素的id属性的值   
        String id2 = preparents.attributeValue("id");   
        // 取得preparents元素下子元素tabname的值,并与id2配对存储   
        uploadMap.put(id2,   
            StringUtils.trim(preparents.elementText("tabname")));     
      }   
      return uploadMap;   
}   
}  

简单代码为如下:

Document document=new SAXReader.reader(“xml文路径/文件名xxx.xml”);
Element root = document.getRootElement();  

HashMap hm = new HashMap<String,String>();   
for ( Iterator iter = root.elementIterator(); iter.hasNext(); )
{   Element element = (Element) iter.next();
    Attribute ageAttr=element.attribute("age");
        String age = ageAttr.getValue();   

      。。。。。

for ( Iterator iterInner = element.elementIterator(); iterInner.hasNext(); ) {   

    Element elementInner = (Element) iterInner.next();

    

//遍历college节点开始

if(elementInner.getName().equals("college")){

/添加college的文本

hm.put(elementInner.getName()+ num, elementInner.getText());

//添加college的leader属性

Attribute leaderAttr=elementInner.attribute("leader");

。。。。。如果leaderAttr不是空字符或者其值不为null。。。。。

hm.put(elementInner.getName() + "-"+leaderAttr.getName()+ num,

leaderAttr.getValue());

     }

else{ //遍历非college节点的其它节点   

     hm.put(elementInner.getName()+ num, elementInner.getText());   

}  

 

     

 

<?xml version="1.0" encoding="UTF-8"?>

 

<students>  

    <student age="25"><!--如果没有age属性,默认的为20-->  

        <name>崔卫兵</name>  

        <college>PC学院</college>  

        <telephone>62354666</telephone>  

        <notes>男,1982年生,硕士,现就读于北京邮电大学</notes>  

    </student>  

    <student>  

        <name>cwb</name>  

        <college leader="学院领导">PC学院</college><!--如果没有leader属性,默认的为leader-->  

        <telephone>62358888</telephone>  

        <notes>男,1987年生,硕士,现就读于中国农业大学</notes>  

    </student>  

    <student age="45">  

        <name>xxxxx</name>  

        <college leader="">xxx学院</college>  

        <telephone>66666666</telephone>  

        <notes>注视中,注释中</notes>  

    </student>  

    <student age="">  

        <name>lxx</name>  

        <college>yyyy学院</college>  

        <telephone>88888888</telephone>  

        <notes>注视中111,注释中222</notes>  

    </student>  

</students>  



Dom4jReadExmple.java

package test2;

 

import java.io.File;   

import java.util.HashMap;   

import java.util.Iterator;   

import org.dom4j.Attribute;   

import org.dom4j.Document;   

import org.dom4j.DocumentException;   

import org.dom4j.Element;   

import org.dom4j.io.SAXReader;   

public class Dom4jReadExmple {    

public void iterateWholeXML(String filename,HashMap<String,String> hm){   

SAXReader saxReader = new SAXReader();   

try {   

   Document document = saxReader.read(new File(filename));   

   Element root = document.getRootElement();   

//   用于记录学生编号的变量   

   int num=-1;   

   //遍历根结点(students)的所有孩子节点(肯定是student节点)   

         for ( Iterator iter = root.elementIterator(); iter.hasNext(); ) {   

             Element element = (Element) iter.next();   

             num++;   

    // 获取person节点的age属性的值   

             Attribute ageAttr=element.attribute("age");   

    if(ageAttr!=null){   

     String age = ageAttr.getValue();   

     if (age != null&&!age.equals("")) {   

      hm.put(element.getName() + "-"+ageAttr.getName()+ num, age);   

     } else {   

      hm.put(element.getName() + "-" +ageAttr.getName()+ num, "20");   

     }   

    }else{   

     hm.put(element.getName() + "-age"+ num, "20");   

    }   

             //遍历student结点的所有孩子节点(即name,college,telphone,notes),并进行处理   

             for ( Iterator iterInner = element.elementIterator(); iterInner.hasNext(); ) {   

              Element elementInner = (Element) iterInner.next();   

              if(elementInner.getName().equals("college")){   

               hm.put(elementInner.getName()+ num, elementInner.getText());   

               //获取college节点的leader属性的值   

               Attribute leaderAttr=elementInner.attribute("leader");   

               if(leaderAttr!=null){   

       String leader = leaderAttr.getValue();   

       if (leader != null&&!leader.equals("")) {   

        hm.put(elementInner.getName() + "-"+leaderAttr.getName()+ num, leader);   

       } else {   

        hm.put(elementInner.getName() + "-" +leaderAttr.getName()+ num, "leader");   

       }   

               }else {   

       hm.put(elementInner.getName() + "-leader"+ num, "leader");   

      }   

              }else{   

               hm.put(elementInner.getName()+ num, elementInner.getText());   

              }   

             }   

         }   

  

} catch (DocumentException e) {   

   // TODO Auto-generated catch block   

   e.printStackTrace();   

}   

}   

}   

TestDom4jReadExmple.java

package dom4jExample.read;   

import java.util.HashMap;   

public class TestDom4jReadExmple {   

public static void main(String[] args) {   

     try{   

       //获取解析完后的解析信息   

       HashMap<String,String> hashMap;   

       Dom4jReadExmple drb=new Dom4jReadExmple();   

       //遍历整个XML文件   

       hashMap = new HashMap<String,String>();   

       drb.iterateWholeXML("studentInfo.xml", hashMap);   

       System.out.println("姓名\t年龄\t学院\t学院领导\t电话\t\t备注");   

       for(int i=0;i<hashMap.size();i+=6){   

         int j=i/6;   

         System.out.print(hashMap.get("name"+j)+"\t");   

         System.out.print(hashMap.get("student-age"+j)+"\t");   

         System.out.print(hashMap.get("college"+j)+"\t");   

         System.out.print(hashMap.get("college-leader"+j)+"\t");   

         System.out.print(hashMap.get("telephone"+j)+"\t");   

         System.out.println(hashMap.get("notes"+j)+"\t");   

       }   

     }catch(Exception ex){   

       ex.printStackTrace();   

     }   

   }   

}   

 

 

二、

一个读写操作的例子:

 

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.Iterator;

 

 

 

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;

 

 

public class testXml {

 

public static void main(String[] args) {

 

try {

 

testXml test = new testXml();

test.testWrite();

test.testRead();

 

} catch (Exception e) {

e.printStackTrace();

}

 

}

 

public void testRead() throws Exception{

 

SAXReader reader = new SAXReader();

Document document = reader.read(new FileInputStream("src/output.xml"));

 

 

Element root = document.getRootElement();

 

for (Iterator iter = root.elementIterator(); iter.hasNext();) {

Element element = (Element) iter.next();

System.out.println(element.getText());

System.out.println(element.attributeValue("name"));

System.out.println(element.attributeValue("blog"));

}

 

}

 

public void testWrite() throws Exception{

 

Document document = DocumentHelper.createDocument();

Element root = document.addElement("root");

for(int i=0;i<10;i++){

 

 

Element element1 = root.addElement("user")

.addAttribute("name","Alex"+i)

.addAttribute("id", "id"+i)

.addText("我是信息");

}

 

XMLWriter writer = new XMLWriter(new FileOutputStream("src/output.xml"));

 

writer.write(document);

writer.close();

 

}

 

}

输出的效果:

<?xml version="1.0" encoding="UTF-8"?>

<root>

<user name="Alex0" id="id0">我是信息</user>

<user name="Alex1" id="id1">我是信息</user>

<user name="Alex2" id="id2">我是信息</user>

<user name="Alex3" id="id3">我是信息</user>

<user name="Alex4" id="id4">我是信息</user>

<user name="Alex5" id="id5">我是信息</user>

<user name="Alex6" id="id6">我是信息</user>

<user name="Alex7" id="id7">我是信息</user>

<user name="Alex8" id="id8">我是信息</user>

<user name="Alex9" id="id9">我是信息</user>

</root>




例子:
package com.vastis.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ReadSpringXmlUtil {
        
    public void iterateWholeXML(String filename, HashMap<String, String> hm) throws Exception{

        SAXReader saxReader = new SAXReader();

        try {
            
            Document document = saxReader.read(new File(filename));
            Element root = document.getRootElement();

            //遍历根结点,即第一层
            for (Iterator iter = root.elementIterator(); iter.hasNext();) {
                Element element = (Element) iter.next();
                // 获取id为dataSource的节点的bean
                if(element!=null){
                    Attribute ageAttr = element.attribute("id");
                    if (ageAttr != null && !ageAttr.equals("")) {
                        String id = ageAttr.getValue();
                        if (id != null &&  id.equals("dataSource")) {
                            // 遍历第二层(即driverClassName,url,username,password),并进行处理
                            for (Iterator iterInner = element.elementIterator(); iterInner.hasNext();) {
                                Element elementInner = (Element) iterInner.next();    
                                if(elementInner!=null && !elementInner.equals("")){
                                    //获取name属性
                                    Attribute dsAttr = elementInner.attribute("name");
                                    if(dsAttr!=null && !dsAttr.equals(""))                                        
                                            //下面开启遍历第3层,即4个property
                                            for (Iterator iterThird = elementInner.elementIterator(); iterThird
                                            .hasNext();) {
                                                Element elementThird = (Element) iterThird.next();
                                                if(elementThird!=null && !elementThird.equals("")){
                                                    if(elementThird.getName().equals("value")){
                                                        hm.put(dsAttr.getValue(), elementThird.getText());
//                                                        System.out.println("name="+elementThird.getName());
//                                                        System.out.println("value="+elementThird.getText());
                                                    }
                                                }
                                                
                                            }
                                }
                                
                            }
                        }
                    }

                    
                }
            
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new Exception(e);
        }
    }
    
}

/**
     * 读取数据库配置,从spring.conf.xml中读取
     * @throws Exception
     */
    private void configDBInfo() throws Exception{        
        HashMap<String, String> hashMap= new HashMap<String, String>();
        ReadSpringXmlUtil rsxu=new ReadSpringXmlUtil();
        rsxu.iterateWholeXML(FILE_PATH,hashMap);
        try{
            if(hashMap!=null && hashMap.size()>0){
                for(java.util.Iterator  iter=hashMap.keySet().iterator();iter.hasNext();){
                    Object key=iter.next();
                    String value=hashMap.get(key);
                    if(((String)key).equals(Constants.URL)){
                        ReadOnlyConfiger.setUrl(value);
                    }else if(((String)key).equals(Constants.USERNAME)){
                        ReadOnlyConfiger.setUserName(value);
                    }else if(((String)key).equals(Constants.PASSWORD)){
                        ReadOnlyConfiger.setPassword(value);
                    }
                }
            }else{
                System.err.println("数据库配置信息未找到,请查看spring.conf.xml文件中的数据配置信息是否存在!");
            }
        }catch(Exception ex){
            System.out.println(ex.toString());
            throw new Exception(ex);
        }
    } 

xml源文件如下

<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  	<!--JDBC数据源配置-->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName">
			<value>oracle.jdbc.driver.OracleDriver</value>
		</property>
		<property name="url">
			<value>jdbc:oracle:thin:@11.5.56.199:1521/caqa</value>
		</property>
		<property name="username">
			<value>system</value>
		</property>
		<property name="password">
			<value>admin</value>
		</property>
	</bean>
  
	<!-- hibernate 配置文件 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource"/>
		</property>
		<property name="configLocation">
	    	<value>/WEB-INF/classes/conf/hibernate.cfg.xml</value>
	  	</property>
	</bean>
	
	<!-- hibernate 事务工厂 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	  <property name="sessionFactory">
	    <ref local="sessionFactory"/>
	  </property>
	</bean>

	<!-- hibernate 事务代理 -->
	<bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
	  <property name="transactionManager">
	    <ref bean="transactionManager"/>
	  </property>
	  <property name="transactionAttributes">
	    <props>
	      <prop key="save*">PROPAGATION_REQUIRED</prop>
	      <prop key="Create*">PROPAGATION_REQUIRED</prop>
	      <prop key="create*">PROPAGATION_REQUIRED</prop>
	      <prop key="add*">PROPAGATION_REQUIRED</prop>
	      <prop key="update*">PROPAGATION_REQUIRED</prop>
	      <prop key="copy*">PROPAGATION_REQUIRED</prop>
	    </props>
	  </property>
	</bean>

	<!--JDBC事务工厂-->
	<bean id="JDBCtransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	  <property name="dataSource">
	    <ref local="dataSource"/>
	  </property>
	</bean>
  
	<!--JDBC 事务代理-->
	<bean id="JDBCDAOProxy" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
	  <property name="transactionManager">
	    <ref bean="JDBCtransactionManager"/>
	  </property>
	  <property name="transactionAttributes">
	    <props>
	      <prop key="insert*">PROPAGATION_REQUIRED</prop>
	      <prop key="update*">PROPAGATION_REQUIRED</prop>
	      <prop key="delete*">PROPAGATION_REQUIRED</prop>
	      <prop key="*">PROPAGATION_REQUIRED</prop>
	    </props>
	  </property>
	</bean>

  <!-- base -->
  <!-- base:project -->
  <bean id="projectDAO" class="com.vastis.base.project.dao.impl.ProjectDAOHibernateImpl">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
  <bean id="projectFacade" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.base.project.service.impl.ProjectFacadeImpl">
        <property name="projectDAO">
          <ref bean="projectDAO"/>
        </property>
      </bean>
    </property>
  </bean>
  <bean id="projectHelper" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.base.project.service.impl.ProjectHelperImpl">
        <property name="projectDAO">
          <ref bean="projectDAO"/>
        </property>
      </bean>
    </property>
  </bean>
  <!-- end base:project -->

  <!--base:param-->
  <bean id="paramDAO" class="com.vastis.base.param.dao.impl.ParamDAOHibernateImpl">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
  <bean id="paramHelper" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.base.param.service.impl.ParamHelperImpl">
        <property name="paramDAO">
          <ref bean="paramDAO"/>
        </property>
      </bean>
    </property>
  </bean>
  <bean id="paramFacade" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.base.param.service.impl.ParamFacadeImpl">
        <property name="paramDAO">
          <ref bean="paramDAO"/>
        </property>
      </bean>
    </property>
  </bean>
  <!-- end base:param -->

  <!--ccms:qamonitor-->
  <bean id="qaMonitorDAOHibernate" class="com.vastis.ccms.qamonitor.dao.impl.QAMonitorDAOHibernateImpl">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>

  <bean id="QamonitorFacade" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.ccms.qamonitor.service.impl.QAMonitorFacadeImpl">
        <property name="qaMonitorDAOHibernate">
          <ref bean="qaMonitorDAOHibernate"/>
        </property>
      </bean>
    </property>
  </bean>
  <bean id="QamonitorHelper" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.ccms.qamonitor.service.impl.QAMonitorHelperImpl">
        <property name="qamonitorDAOHibernate">
          <ref bean="qaMonitorDAOHibernate"/>
        </property>
      </bean>
    </property>
  </bean>
  <!-- end ccms:qamonitor-->
  
  <!-- start ccms:staff -->
  <bean id="staffDAO" class="com.vastis.ccms.staff.dao.impl.StaffDAOHibernateImpl">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
  
   <bean id="staffJDBCDAO" class="com.vastis.ccms.staff.dao.impl.StaffDAOJDBCImpl">
    <property name="dataSource">
      <ref local="dataSource"/>
    </property>
  </bean>
    
  <bean id="staffFacade" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.ccms.staff.service.impl.StaffFacadeImpl">
        <property name="staffDAOHibernate">
          <ref bean="staffDAO"/>
        </property>
        <property name="staffDAOJDBC">
          <ref bean="staffJDBCDAO"/>
        </property>
      </bean>
    </property>
  </bean>

  <bean id="staffHelper" parent="txProxyTemplate">
    <property name="target">
      <bean class="com.vastis.ccms.staff.service.impl.StaffHelperImpl">
        <property name="staffDAOHibernate">
          <ref bean="staffDAO"/>
        </property>
        <property name="staffDAOJDBC">
          <ref bean="staffJDBCDAO"/>
        </property>
      </bean>
    </property>
  </bean>
  <!-- end ccms:staff -->	
	
  <bean id="MenuManagerFacade" class="com.vastis.menu.service.FacadeImpl"/>
  <bean id="MenuManagerHelper" class="com.vastis.menu.service.MenuManagerHelperImpl"/>

	<bean id="securityFacade" parent="txProxyTemplate">
	   <property name="target">
	     <bean class="com.vastis.security.service.impl.SecurityFacadeImpl">
	     </bean>
	   </property>
	</bean>
</beans>





你可能感兴趣的:(DOM4j SAXReader 读取XML文件)