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

  /**
   *    * class="com.mystruts.demo.LoginAction">   * url="hello.jsp"/>   * path="/user" class="com.mystruts.demo.UserAction">   * name="success" url="list.jsp"/>
   */

  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

你可能感兴趣的:(Java技术,XML技术)