Java應用Jdom讀取xml解析實例。本站提示廣大學習愛好者:(Java應用Jdom讀取xml解析實例)文章只能為提供參考,不一定能成為您想要的結果。以下是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法式設計有所贊助。