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

JSP
写 bean 类的准则
Jsp问答集一
JSP内幕
多个域名绑定一个空间互不影响
建立JSP操作提高数据库访问效率
教你用Javascript制作连续滚动的字幕
JSP中的TagLib应用(1)
JSP中的TagLib应用(2)
JSP中的TagLib应用(4-3)
JSP中的TagLib应用(4-4)
Eclipse 3.0 上配置JSP开发环境
JAVA/JSP学习系列之一
JAVA/JSP学习系列之二
JAVA/JSP学习系列之三
JAVA/JSP学习系列之四
JAVA/JSP学习系列之五
JAVA/JSP学习系列之六
JAVA/JSP学习系列之七
在Linux环境下安装JSP(一)
在Linux环境下安装JSP(二)

JSP提供解析接口的XML数据


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 46 ::
收藏到网摘: 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>