dom4j解析xml文件

dom4j解析xml文件

1.先导入dom4j-1.6.1.jar包
2.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<config>
 
 
 <action name="user" className="com.kaishengit.web.UserAction">
  <result name="success" type="forward">suc.jsp</result>
  <result name="error" type="redirect">404.jsp</result>
 </action>
 
 
 <action name="book" className="com.kaishengit.web.BookAction">
  <result name="success">book.jsp</result>
  <result name="error" type="redirect">bookerror.jsp</result>
 </action>
 
 <action name="person" className="com.kaishengit.web.PersonAction" method="del">
  <result name="ok">suc.jsp</result>
 </action>
 
 

</config>

3.解析测试类是:

package com.kaishengit.test;

import java.io.File;
import java.net.URL;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jTest {

 public void readXML() {
  //拿到src文件夹里的xml配置文件
  URL url = getClass().getResource("/");
  System.out.println(url);
  String filePath = url.getFile() + "struts.xml";
  
  try {
   //创建读取配置文件的对象
   SAXReader reader = new SAXReader();
   //开始读取配置文件
   Document doc = reader.read(new File(filePath));
   //拿到根节点
   Element root = doc.getRootElement();
   
   //拿到根节点下的action接点数组
   List<Element> actions = root.elements("action");
   
   for(Element action : actions) {
    String name = action.attributeValue("name");
    String className = action.attributeValue("className");
    String method = action.attributeValue("method");
    System.out.println("name="+name);
    System.out.println("className="+className);
    System.out.println("method="+method);
    
    List<Element> results = action.elements("result");
    for(Element result : results) {
     String resultName = result.attributeValue("name");
     String resultType = result.attributeValue("type");
     String pageName = result.getText();
     
     System.out.println("name:" + resultName + "\tresultType:" + resultType + "\tpageName:" + pageName);
   
    }
    
    System.out.println("----------------------");
   }
   
   
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 
 
 
 public static void main(String[] args) {
  
  
  Dom4jTest d = new Dom4jTest();
  d.readXML();
  
  
  
 }
}

你可能感兴趣的:(dom4j解析xml文件)