7
27
同学要个jsp解析xml的例子,我就答应了
说句实话,好久都没有直接写过jsp了!
解析xml,也都好久没有摸过的东西了啊!
忽然拿起来还有些生疏啊!
随便写了一个,贴出代码和大家分享一下!
JSP文件
< % //建立解析工厂 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //创建解析器 DocumentBuilder db = dbf.newDocumentBuilder(); //得到解析文件 String xml = application.getRealPath("user.xml"); //开始解析xml文件 Document doc = db.parse(new File(xml)); //格式化DOM,也就是去除不必要的Text Node doc.normalize(); //得到根元素 Element root = doc.getDocumentElement(); //得到所有user元素 NodeList users = root.getElementsByTagName("user"); %> <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++) { Element user = (Element) users.item(i); %> <tr> <td>< %=user.getElementsByTagName("id").item(0) .getFirstChild().getNodeValue()%></td> <td>< %=user.getElementsByTagName("firstName").item(0) .getFirstChild().getNodeValue()%></td> <td>< %=user.getElementsByTagName("lastName").item(0) .getFirstChild().getNodeValue()%></td> <td>< %=user.getElementsByTagName("password").item(0) .getFirstChild().getNodeValue()%></td> < % } %> </tr> </table>
要解析的XML文件
<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>
对于高手,这些就没有什么必要了!不过偶尔也是会忘记的啊!温故而知新啊!^_^
随机日志
本站文章除特别标示外,其他文章都属于原创内容,转载请按以下格式注明:
本文来源:舞命小丢
原文链接:http://thinking.5ming.org.cn/2008/07/27/jsp-parse-xml/
TrackBack:http://thinking.5ming.org.cn/2008/07/27/jsp-parse-xml/trackback/
