Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Archives
Today
Total
관리 메뉴

유령노트

XML 파싱 하는방법 본문

JAVA

XML 파싱 하는방법

유령손 2018. 7. 18. 14:02
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