Java使用Jdom读取xml解析实例

本文实例讲述了Java使用Jdom读取xml解析。分享给大家供大家参考,具体如下:

package com.yanek.demo.xml.test;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class JdomReadXml {
 /**
 * @param args
 */
 public static void main(String[] args) {
 /**
  * <?xml version="1.0" encoding="UTF-8"?> <actions m="001"><action
  * path="/test" class="com.mystruts.demo.LoginAction"><forward
  * name="success" url="test.jsp" /><forward name="failure"
  * url="failure.jsp" /></action><action path="/user"
  * class="com.mystruts.demo.UserAction"><forward name="success"
  * url="test.jsp" /><forward name="failure" url="failure.jsp" /></action></actions>
  */
 SAXBuilder sax = new SAXBuilder();
 Document doc;
 try {
  try {
  doc = sax.build(new File("mystruts.xml"));
  Element root = doc.getRootElement();
  List actions = root.getChildren();
  // 遍历获取根节点下的一级子节点,并作为入参传入递归方法
  for (Iterator i = actions.iterator(); i.hasNext();) {
   Element action = (Element) i.next();
   System.out.println(action.getAttributeValue("path"));
   System.out.println(action.getAttributeValue("class"));
   List forwards = action.getChildren();
   for (Iterator j = forwards.iterator(); j.hasNext();) {
   Element forward = (Element) j.next();
   System.out.println(forward.getAttributeValue("name"));
   System.out.println(forward.getAttributeValue("url"));
   }
  }
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 } catch (JDOMException e) {
  e.printStackTrace();
 }
 }
}

输出:

/test
com.mystruts.demo.LoginAction
success
test.jsp
failure
failure.jsp
/user
com.mystruts.demo.UserAction
success
test.jsp
failure
failure.jsp

希望本文所述对大家Java程序设计有所帮助。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。