1 public String viewPic(HttpServletRequest request, String id) {
2 //创建Document对象及读取XML文件
3 DocumentBuilderFactory builderFactory = DocumentBuilderFactory
4 .newInstance();
5 //解析XML
6 Document document=null;
7 try {
8 DocumentBuilder builder = builderFactory.newDocumentBuilder();
9
10 document = builder.parse(new File(request.getSession()
11 .getServletContext().getRealPath(
12 "/WEB-INF/classes/MyXml.xml")));
13 } catch (ParserConfigurationException e) {
14 e.printStackTrace();
15 } catch (SAXException e) {
16 e.printStackTrace();
17 } catch (IOException e) {
18 e.printStackTrace();
19 }
20 Element rootElement = document.getDocumentElement(); //获取根节点
21 NodeList childNodes = rootElement.getChildNodes(); //根节点下所有子节点
22
23 for (int i = 0; i < childNodes.getLength(); i++) { //循环第一层子节点
24 Node childNode = childNodes.item(i);
25 NodeList childNodes_2 = childNode.getChildNodes();
26 for(int j = 0;j < childNodes_2.getLength();j++){ //循环第二层子节点
27 Node childNode_2 = childNodes_2.item(j);
28 NodeList childNodes_3 = childNode_2.getChildNodes();
29 for(int k = 0;k < childNodes_3.getLength();k++){ //第三层
30 Node childNode_3 = childNodes_3.item(k);
31 System.out.println(childNode_3.getNodeValue());
32 }
33 }
34 }
35
36 return "img_1.jsp";
37 }
1//XML文件
2 <?xml version="1.0" encoding="UTF-8"?>
3 <xml-body>
4 <link id="1">
5 <name>http://localhost:8080/tgklx/</name>
6 </link>
7 </xml-body>