展示如何在 JSP 中解析 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>
<%@ 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 僅負責解析呈現。