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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值