dom4j解析xml文件实例

dom4j解析xml文件实例

 

 

package com.yanek.demo.xml.test;

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

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

public class Dm4jReadXml {

 /**
  * @param args
  */
 public static void main(String[] args) {

  // dom4j读xml,解析xml

  /**
   * <?xml version="1.0" encoding="UTF-8"?> <actions><action path="/test"
   * class="com.mystruts.demo.LoginAction"><forward name="success"
   * url="hello.jsp"/><forward name="fail" url="fail.jsp"/></action><action
   * path="/user" class="com.mystruts.demo.UserAction"><forward
   * name="success" url="list.jsp"/><forward name="fail" url="fail.jsp"/></action></actions>
   */

  SAXReader saxReader = new SAXReader();
  try {
   Document document = saxReader.read(new File("d://mystruts.xml"));
   Element root = document.getRootElement();

   List actions = root.elements("action");

   for (int i = 0; i < actions.size(); i++) {
    Element action = (Element) actions.get(i);
    System.out.println("action.path=="
      + action.attributeValue("path"));
    System.out.println("action.class=="
      + action.attributeValue("class"));

    List forwards = action.elements("forward");
    for (int j = 0; j < forwards.size(); j++) {

     Element forward = (Element) forwards.get(j);
     System.out.println("forward.name=="
       + forward.attributeValue("name"));
     System.out.println("forward.url=="
       + forward.attributeValue("url"));
    }

   }

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

 }

}

 

执行结果:

 

action.path==/test
action.class==com.mystruts.demo.LoginAction
forward.name==success
forward.url==hello.jsp
forward.name==fail
forward.url==fail.jsp
action.path==/user
action.class==com.mystruts.demo.UserAction
forward.name==success
forward.url==list.jsp
forward.name==fail
forward.url==fail.jsp

上一篇:sqlplus连接数的测试


下一篇:JAVA常用类之格式化