標籤:jdom讀取xml檔案
<%@ page contentType="text/html; charset=gb2312" language="java" %><%@ page import="java.io.*,org.jdom.*,org.jdom.input.*,org.jdom.output.*,java.util.List,java.util.Iterator" %><html><head><title>用JDOM解析並輸出user.xml</title></head><body><table><!-- 輸出表頭 --><tr><td>使用者ID</td><td>使用者名稱</td><td>密碼</td><td>真實姓名</td><td>年齡</td><td>性別</td></tr><% // 得到資料SAXBuilder builder=new SAXBuilder(); // 建立對象// 建立Document對象 Document readDocument=builder.build(pageContext.getServletContext().getResourceAsStream("/user.xml")); // 注意:user.xml檔案要和該檔案放到一個檔案夾下,具體原因現在不太清楚,是實驗得到的// 得到根項目 Element rootElement=readDocument.getRootElement();// 得到根項目的子項目列表,實際上就是user元素列表List list=rootElement.getChildren();// 輸出資料for(Iterator i=list.iterator();i.hasNext();){Element current=(Element)i.next();out.println("<tr>");// 輸出使用者ID號out.println("<td>"+current.getChildText("id")+"</td>");// 輸出使用者名稱out.println("<td>"+current.getChildText("name")+"</td>");// 輸出使用者密碼out.println("<td>"+current.getChildText("password")+"</td>");// 輸出真實姓名out.println("<td>"+current.getChildText("true_name")+"</td>");// 輸出使用者年齡out.println("<td>"+current.getChildText("age")+"</td>");// 輸出使用者性別out.println("<td>"+current.getChildText("sex")+"</td>");out.println("</tr>");} %></table></body></html>