1.接口內容如下:
<?xml version="1.0" encoding="UTF-8"?> <users> <user> <id>1</id> <firstname>Song</firstname> <lastname>Thinking</lastname> <password>songlipeng</password> </user> <user> <id>2</id> <firstname>Zheng</firstname> <lastname>Quanling</lastname> <password>zhengquanling</password> </user> </users>
2.解析的JSP代碼如下:
<%@ page language="java" import="java.util.*,javax.xml.parsers.*,java.sql.*" pageEncoding="UTF-8"%> <%@ page import="java.io.*,javax.xml.*,org.w3c.dom.*" %> <% //建立解析工廠 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); //忽略元素內容中的空格 //創建解析器 DocumentBuilder db = dbf.newDocumentBuilder(); //得到解析文件 //據說這樣寫可以讓XML與JSP放在同一目錄哦 Document doc = db.parse("http://localhost:8080/MyProjects/webserver/users.xml"); //得到其他地方的接口目錄 doc.normalize(); //得到根元素 //Element root = doc.getDocumentElement(); //得到所有user元素 NodeList users = doc.getElementsByTagName("user"); NodeList usersIdNodeList= doc.getElementsByTagName("id"); NodeList usersNameNodeList= doc.getElementsByTagName("firstname"); NodeList usersPasswordNodeList=doc.getElementsByTagName("lastname"); NodeList usersTrueNameNodeList=doc.getElementsByTagName("password"); %> <table> <thead> <tr> <th>ID</th> <th>firstName</th> <th>lastName</th> <th>password</th> </tr> </thead> <% Node userNode = null; for (int i = 0; i < users.getLength(); i++) { //Element user = (Element) users.item(i); %> <tr> <td><%=usersIdNodeList.item(i).getFirstChild().getNodeValue()%></td> <td><%=usersNameNodeList.item(i).getFirstChild().getNodeValue()%></td> <td><%=usersPasswordNodeList.item(i).getFirstChild().getNodeValue()%></td> <td><%=usersTrueNameNodeList.item(i).getFirstChild().getNodeValue()%></td> <% } %> </tr> </table> <!--只提取XML中的ID數據信息--> <center> <% for(int i=0;i<usersIdNodeList.getLength();i++){ out.println("<b>"+usersIdNodeList.item(i).getFirstChild().getNodeValue()+"</b>"); } %> </center>
所以XML的話可以這樣其他地方是JAVA來將數據寫入 然後我在這裡解析出來!