javaweb jsp解析xml文件

2025-05-23 06:53:10

1、新建xml文件,在根目录添加xml文档,然后刷新。F:\Program Files\MyEclipse\workspace\Day05\WebRootroom.xml<空闲自习室数据> <room> <weekday>1</weekday> <place>0</place> <time>0</time> <class>1-109</class> </room> <room> <weekday>1</weekday> <place>3</place> <time>0</time> <class>4-309</class> </room></空闲自习室数据>

javaweb jsp解析xml文件

2、添加read.jsp文件,粘贴即可。<%@ page language="java"稆糨孝汶; import="javax.xml.parsers.*,org.w3c.dom.*" pageEncoding="utf-8"%><!-- 载入XML需的包 --><html><head><title>XMLRead</title></head><body> <% DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(request.getSession().getServletContext().getRealPath("room.xml"));//建立Document对象,并设置文件路径参数 Element e = d.getDocumentElement();//取得代表整个XML文件内容的元素对象 NodeList nl = e.getElementsByTagName("room");//从XML元素当中萃取出所有包含名称为customer的节点集合对象NodeList //依次将节点集合当中的元素并逐一取出显示在页面上 for (int i = 0; i < nl.getLength(); i++) { Element childElement = (Element) nl.item(i);//取得目前索引位置的元素 NodeList childNodeList = null; String outString = ""; //取得此元素底下的所有节点集合 childNodeList = childElement.getElementsByTagName("weekday"); outString = childNodeList.item(0).getFirstChild().getNodeValue(); out.println("weekday:" + outString + "<br>"); childNodeList = childElement.getElementsByTagName("place"); outString = childNodeList.item(0).getFirstChild().getNodeValue(); out.println("place:" + outString + "<br>"); childNodeList = childElement.getElementsByTagName("time"); outString = childNodeList.item(0).getFirstChild().getNodeValue(); out.println("time:" + outString + "<br>"); childNodeList = childElement.getElementsByTagName("class"); outString = childNodeList.item(0).getFirstChild().getNodeValue(); out.println("class:" + outString + "<br>"); out.println("<p>"); } %></body></html>

javaweb jsp解析xml文件

3、浏览器显示如下

javaweb jsp解析xml文件
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢