<images> <item> <ImageID>1</ImageID> <ItemID>Item 01</ItemID> <ImagePath>https://www.thaicreate.com/android/images/img01.gif</ImagePath> <Link>https://www.thaicreate.com/page-1.html</Link> </item> <item> <ImageID>2</ImageID> <ItemID>Item 02</ItemID> <ImagePath>https://www.thaicreate.com/android/images/img02.gif</ImagePath> <Link>https://www.thaicreate.com/page-2.html</Link> </item> <item> <ImageID>3</ImageID> <ItemID>Item 03</ItemID> <ImagePath>https://www.thaicreate.com/android/images/img03.gif</ImagePath> <Link>https://www.thaicreate.com/page-3.html</Link> </item> </images>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %> <%@ page import="javax.xml.parsers.DocumentBuilder" %> <%@ page import="org.w3c.dom.Document" %> <%@ page import="org.w3c.dom.NodeList" %> <%@ page import="org.w3c.dom.Node" %> <%@ page import="org.w3c.dom.Element" %> <%@ page import="java.io.File" %> <%@ page import="java.util.ArrayList" %> <%@ page import="java.util.HashMap" %> <html> <head> <title>ThaiCreate.Com JSP Tutorial</title> </head> <body> <% try { String fileName = application.getRealPath("/data/myData.xml"); File strXML = new File(fileName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbf.newDocumentBuilder(); Document doc = dBuilder.parse(strXML); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("item"); ArrayList<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map; for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element ele = (Element) nNode; map = new HashMap<String, String>(); map.put("ImageID", ele.getElementsByTagName("ImageID") .item(0).getTextContent()); map.put("ItemID", ele.getElementsByTagName("ItemID") .item(0).getTextContent()); map.put("ImagePath", ele.getElementsByTagName("ImagePath") .item(0).getTextContent()); map.put("Link", ele.getElementsByTagName("Link").item(0) .getTextContent()); myArrList.add(map); } } // *** Print Result ***// for (int i = 0; i < myArrList.size(); i++) { String sImageID = myArrList.get(i).get("ImageID").toString(); String sItemID = myArrList.get(i).get("ItemID").toString(); String sImagePath = myArrList.get(i).get("ImagePath") .toString(); String sLink = myArrList.get(i).get("Link").toString(); out.println("<br>ImageID = " + sImageID); out.println("<br>ItemID = " + sItemID); out.println("<br>ImagePath = " + sImagePath); out.println("<br>Link = " + sLink); out.println("<br>========================="); } } catch (Exception e) { e.printStackTrace(); } %> </body> </html>
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท