首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP XML 資料解析介面範例

     編輯:關於JSP

展示如何在 JSP 中解析 XML 資料並以表格顯示。

XML 資料

<?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>

JSP 解析代碼

<%@ page import="java.util.*,javax.xml.parsers.*,java.sql.*,java.io.*,javax.xml.*,org.w3c.dom.*" %>
<%
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setIgnoringElementContentWhitespace(true);
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse("https://localhost:8080/MyProjects/webserver/users.xml");
  doc.normalize();
  NodeList users = doc.getElementsByTagName("user");
  NodeList ids = doc.getElementsByTagName("id");
  NodeList firstNames = doc.getElementsByTagName("firstname");
  NodeList lastNames = doc.getElementsByTagName("lastname");
  NodeList passwords = doc.getElementsByTagName("password");
%>
<table><thead><tr><th>ID</th><th>firstName</th><th>lastName</th><th>password</th></tr></thead>
<%
  for (int i = 0; i < users.getLength(); i++) {
%>
  <tr>
    <td><%=ids.item(i).getFirstChild().getNodeValue()%></td>
    <td><%=firstNames.item(i).getFirstChild().getNodeValue()%></td>
    <td><%=lastNames.item(i).getFirstChild().getNodeValue()%></td>
    <td><%=passwords.item(i).getFirstChild().getNodeValue()%></td>
  </tr>
<% } %>
</table>

此法適用於 XML 資料由其他 Java 程式產生,JSP 僅負責解析呈現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved