유령노트
XML 파싱 하는방법 본문
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | package test; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class test { public static void main(String[] args) { try { // parsing할 url 지정(API 키 포함해서) String url = "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4613032000"; DocumentBuilderFactory dbFactoty = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactoty.newDocumentBuilder(); Document doc = dBuilder.parse(url); // root tag doc.getDocumentElement().normalize(); System.out.println("Root element: " + doc.getDocumentElement().getNodeName()); // Root element: result // 파싱할 tag NodeList nList = doc.getElementsByTagName("data"); System.out.println("파싱할 리스트 수 : "+ nList.getLength()); // 파싱할 리스트 수 : 5 for(int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("######################"); //System.out.println(eElement.getTextContent()); System.out.println("시간 : " + getTagValue("hour", eElement)); System.out.println("온도 : " + getTagValue("temp", eElement)); System.out.println("닐씨 : " + getTagValue("sky", eElement)); } // for end } // if end } catch(Exception e) { System.out.println(e.toString()); } } // tag값의 정보를 가져오는 메소드 private static String getTagValue(String tag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); if(nValue == null) return null; return nValue.getNodeValue(); } } | cs |
'JAVA' 카테고리의 다른 글
JAVA 해당 일자 일주일 범위 구하기용 (0) | 2019.02.13 |
---|---|
JAVA에서 ArrayList 또는 HashMap 가져올때 StringJSON 형태로 가져오는 방법 (0) | 2019.02.12 |
자바 캘린더 클래스로 일주일의 시작과 끝 날짜 구하기 (0) | 2019.01.10 |
List<HashMap<String, Object>> 정렬 (0) | 2018.02.13 |
poi 라이브러리 엑셀 다운 예제 (0) | 2017.12.29 |