当前位置: 首页 > 图文教程 > 网络编程 > JSP > JSP提供解析接口的XML数据

JSP
JSP连接各类数据库大全(上)
JSP连接各类数据库大全(下)
JSP在win2000下的安装
JSP及语法概要
JSP中文问题解决方案
JSP连接SQL SERVER问题总结
在windows环境下安装tomcat
在NT上安装Apache+Servlet+jsp
jsp与ejb通信
关于JSP写文件的补充
win2k在apache1.3上配置tomcat3.1
在Linux上安装Tomcat
JSP数据库操作例程 - 数据分页显示 - JDBC 2.0 - Oracle
JSP数据库操作例程 - 存储过程 - JDBC-ODBC - SQL Server - 1.1版本
JSP实现在浏览器关闭cookies情况下的会话管理
jsp源码实例2(获取表单参数)
jsp源码实例1(输出)
JSP文件操作例程 - 读文件
在JSP中写text文件
在Linux上架设支持JSP+PHP的Web服务器

JSP提供解析接口的XML数据


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 44 ::
收藏到网摘: n/a

  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数据信息-->
  <div>
  <%
  for(int i=0;i<usersIdNodeList.getLength();i++){
  out.println("<b>"+usersIdNodeList.item(i).getFirstChild().getNodeValue()+"</b>");
  }
  %>
  </div>