您现在的位置:计算机技术学习网 > 技术中心 > WEB编程 > JSP >

JSP提供解析接口的XML数据代码示例参考

来源:互联网 责任编辑:栏目编辑 发表时间:2013-07-01 11:04 点击:
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>
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • JSP与Servlet
  • 自己动手写MiniBBS系列(基本篇)之用户登录
  • JSP取当前日期
  • JDBC 入门(一)
  • 打开一个jsp页面默认查询所有数据,调用action
  • 使用JSP标签库验证用户的输入(2)完
  • WIN98/2000下的jsp服务器
  • 自定义JSP标签(tag)浅议
  • Struts学习傻瓜式入门篇
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1