Java使用Jdom读取xml解析实例
程序员文章站
2024-03-07 17:29:57
本文实例讲述了java使用jdom读取xml解析。分享给大家供大家参考,具体如下:
package com.yanek.demo.xml.test;
impor...
本文实例讲述了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程序设计有所帮助。