상세 컨텐츠

본문 제목

java xml parser 예제 (자바 xml 파싱)

프로그램 언어/Java

by husks 2015. 5. 19. 17:16

본문

반응형


오픈 api xml 파일을 파싱하는 예제 입니다.

아래는 xml예제 입니다.


test.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<list>
    <Parent>
        <Child1>123</Child1>
        <Child2>홍길동전</Child2>
        <Child3>허균</Child3>
    </Parent>
    <Parent>
        <Child1>124</Child1>
        <Child2>레미제라블</Child2>
        <Child3>빅토르 위고</Child3>
    </Parent>
</list>




XmlParsering.java
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
62
63
64
65
66
67
68
69
70
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
 
public class XmlParsering {
 
    public static void main(String[] args) {
 
        try{
 
            new XmlParsering().start();
 
        }catch (Exception e){
            e.printStackTrace();
        }
 
    }
 
    private void start() throws Exception{
        URL url = new URL("xml 주소입력");
        URLConnection connection = url.openConnection();
 
        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("Parent");
 
        for(int i=0; i<descNodes.getLength();i++){
 
            for(Node node = descNodes.item(i).getFirstChild(); node!=null; node=node.getNextSibling()){ //첫번째 자식을 시작으로 마지막까지 다음 형제를 실행
 
                if(node.getNodeName().equals("Child1")){
                    System.out.println(node.getTextContent());
                }else if(node.getNodeName().equals("Child2")){
                    System.out.println(node.getTextContent());
                }else if(node.getNodeName().equals("Child3")){
                    System.out.println(node.getTextContent());
                }
 
            }
 
        }
    }
 
    private Document parseXML(InputStream stream) throws Exception{
 
        DocumentBuilderFactory objDocumentBuilderFactory = null;
        DocumentBuilder objDocumentBuilder = null;
        Document doc = null;
 
        try{
 
            objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
 
            doc = objDocumentBuilder.parse(stream);
 
        }catch(Exception ex){
            throw ex;
        }       
 
        return doc;
    }
 
}



참고: http://stackoverflow.com/questions/3058434/xml-parse-file-from-http


반응형

관련글 더보기

댓글 영역