<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>
package com.java.myapp; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; import java.util.ArrayList; import java.util.HashMap; public class MyClass { public static void main(String[] args) { try { File strXML = new File("C:\\java\\myData.xml"); 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(); System.out.println("ImageID = " + sImageID); System.out.println("ItemID = " + sItemID); System.out.println("ImagePath = " + sImagePath); System.out.println("Link = " + sLink); System.out.println("========================="); } } catch (Exception e) { e.printStackTrace(); } } }
String url = "https://www.thaicreate.com/data.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new URL(url).openStream());
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท