본문 바로가기
IT 개발/JAVA

XML 파싱 - JAXB marshal, unmarshal (마샬, 언마샬)

by Love of fate 2020. 10. 6.
728x90
반응형

[XML 파싱 - JAXB marshal, unmarshal (마샬, 언마샬)]

 

 

[건축허가인 데이터 가져오기 ]

- www.data.go.kr/data/15044678/openapi.do


JAXB

- 자바의 XML을 파싱 (분석)할 수 있게 도와주는 라이브러리로 JAXB가 있다. JAX는 XML과 자바클래스를 바인딩(연결)

  한다. 간단한 명령어만으로 클래스에 파싱된 XML을 대입해주는 라이브러리이다.

 

- 기존의 XML 분석 방법은 XML 전체를 String 형식으로 받아와서 문자열을 자르는 방식이었다. 

  JAXB는 원하는 태그명, 어트리뷰트명을 기입한 클래스를 마련해두기만 하면 자동적으로 값이 클래스에 들어오게 되는

  자동화 라이브러리이다. 

 

* 마샬 (Marshal)

  - 객체를 XML로 변환

 

* 언마샬 (Unmarshal)

  - XML을 객체로 변환 

  - XML은 태그로 되어 있는데 @XmlElement(name = "resultCode") 와 같이 이름을 맞춰줘야

    데이터를 가져올 수 있다.


[ Spring Boot Project로 제작 ]

 

* pom.xml

  - lombok 의존성 추가 (필요시, 필수 X)

  - lombok의 역할

    - Lombok은 자바 클래스에서 Getter/Setter와 같은 메서드들을 어노테이션을 이용해서

      자동으로 생성 해주는 기능을 제공해주는 툴

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.20</version>
		</dependency>

 

* application properties

# Web ContextRootPath and PortNumber Settings
server.servlet.context-path=/
server.port=8080

# JSP Path (ViewResolver)
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

#builder_permission API kEY
restApi.key : --- API KEY ---
restApi.basisUrl : http://apis.data.go.kr/1611000/ArchPmsService/getApBasisOulnInfo?ServiceKey=
restApi.apDongOulnUrl : http://apis.data.go.kr/1611000/ArchPmsService/getApDongOulnInfo?ServiceKey=
restApi.apFlrOulnUrl : http://apis.data.go.kr/1611000/ArchPmsService/getApFlrOulnInfo?ServiceKey=
restApi.apHoOulnUrl : http://apis.data.go.kr/1611000/ArchPmsService/getApHoOulnInfo?ServiceKey=

 

*Controller

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.enjoybt.builder.permission.vo.JaxbBasisVO;
 
//@RestController
@Controller
public class MainController {
 
    @Value("${restApi.key}")
    private String restApiKey;
    
    @Value("${restApi.basisUrl}")
    private String basisUrl;
    
    @Value("${restApi.apDongOulnUrl}")
    private String apDongOulnUrl;
    
    @Value("${restApi.apFlrOulnUrl}")
    private String apFlrOulnUrl;
    
    @Value("${restApi.apHoOulnUrl}")
    private String apHoOulnUrl;
    
    @RequestMapping(value = "/restApi.do", method= {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> restApi(
        @RequestParam(value = "sigunguCd"String sigunguCd,
        @RequestParam(value = "bjdongCd"String bjdongCd,
        @RequestParam(value = "platGbCd"String platGbCd,
        @RequestParam(value = "bun"String bun,
        @RequestParam(value = "ji"String ji,
        @RequestParam(value = "serviceKey"String serviceKey
        ) {
        Map<String, Object> result = new HashMap<String, Object>();    
        HttpURLConnection connect = null;
        
        String [] arrUrl = {basisUrl, apDongOulnUrl, apFlrOulnUrl, apHoOulnUrl};
        String [] arrName = {"BASIS""APDONG""APFLR""APHO"};
        
        try {
                String urlstr = arrUrl[0+ restApiKey + "&sigunguCd=" + sigunguCd + "&bjdongCd=" + bjdongCd 
                        + "&platGbCd=" + platGbCd + "&bun=" + bun + "&ji=" + ji;
                        //GET방식으로 받게끔 되어있는 API라서 URL로 달 수 밖에 없다.
                        //returnType을 Json으로 받고 싶다면 "&_returnType=json"를 추가해주면 된다.
                URL url = new URL(urlstr); 
                
                connect = (HttpURLConnection) url.openConnection();
                connect.setRequestMethod("GET");
                
                JAXBContext jaxbContext = JAXBContext.newInstance(JaxbBasisVO.class);
                Unmarshaller unmarsharller = jaxbContext.createUnmarshaller();
                JaxbBasisVO jaxbBasisVO = (JaxbBasisVO) unmarsharller.unmarshal(url);
                
                if(jaxbBasisVO.body.basisItems.basis != null && jaxbBasisVO.header.resultCode.equals("00")) {
                    result.put(arrName[0], jaxbBasisVO.body.basisItems.basis);
                    
                    for(int i = 1; i < arrUrl.length; i++) {
                        urlstr = arrUrl[i] + restApiKey + "&sigunguCd=" + sigunguCd + "&bjdongCd=" + bjdongCd 
                                + "&platGbCd=" + platGbCd + "&bun=" + bun + "&ji=" + ji;
                        
                        url = new URL(urlstr); 
                        connect = (HttpURLConnection) url.openConnection();
                        connect.setRequestMethod("GET");                    
                        unmarsharller = jaxbContext.createUnmarshaller();
                        
                        jaxbBasisVO = (JaxbBasisVO) unmarsharller.unmarshal(url);
                        result.put(arrName[i], jaxbBasisVO.body.basisItems.basis);                
                    }
                }else {
                    throw new Exception();
                }
            result.put("RESULT""SUCCESS");
        } catch (Exception e) {
            result.put("RESULT""FAILED");
        }
        return result;
    }
}
cs

 

* JaxbVO

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.List;
 
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import org.springframework.web.bind.annotation.GetMapping;
import com.fasterxml.jackson.annotation.JsonGetter;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
 
@Setter
@Getter
@ToString
@XmlRootElement(name = "response")
public class JaxbBasisVO {
 
    @XmlElement(name = "header")
    public Header header;
 
    @XmlElement(name = "body")
    public Body body;
    
    @Setter
    @Getter
    @ToString
    @XmlRootElement(name = "header")
    public static class Header {
 
        @XmlElement(name = "resultCode")
        public String resultCode;
 
        @XmlElement(name = "resultMsg")
        public String resultMsg;
    }
    
    @Setter
    @Getter
    @ToString
    @XmlRootElement(name = "body")
    public static class Body {
            
        @XmlElement(name = "items")
        public BasisItems basisItems;
            
        @XmlElement(name = "numOfRows")
        public Integer numOfRows;
                
        @XmlElement(name = "pageNo")
        public Integer pageNo;
                
        @XmlElement(name = "totalCount")
        public Integer totalCount;
    }
 
    @Setter
    @Getter
    @ToString
    @XmlRootElement(name = "items")
    public static class BasisItems {
 
        @XmlElement(name = "item")
        public List<BasisDataVO> basis;
    
    }
    
    @Setter
    @Getter
    @ToString
    @XmlRootElement(name = "items")
    public static class ApDongItems {
        
        @XmlElement(name = "item")
        public List<ApDongOulnDataVO> apdong;
    
    }
    
    @Setter
    @Getter
    @ToString
    @XmlRootElement(name = "items")
    public static class ApFlrItems {
        
        @XmlElement(name = "item")
        public List<ApFlrOulnDataVO> apflr;
 
    }
    
    @Setter
    @Getter
    @ToString
    @XmlRootElement(name = "items")
    public static class ApHoItems {
    
        @XmlElement(name = "item")
        public List<ApHoOulnDataVO> apho;        
    }
}
 

 

* BasisDataVO

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package com.enjoybt.builder.permission.vo;
 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
 
import lombok.Getter;
import lombok.Setter;
 
@Getter
@Setter
@XmlRootElement(name = "item")
public class BasisDataVO {
    
    @XmlElement(name = "rnum")
    public int rnum;
    
    @XmlElement(name = "platPlc")
    public String platPlc;
 
    @XmlElement(name = "sigunguCd")
    public String sigunguCd;
    
    @XmlElement(name = "bjdongCd")
    public String bjdongCd;
    
    @XmlElement(name = "platGbCd")
    public String platGbCd;
    
    @XmlElement(name = "bun")    
    public String bun;
    
    @XmlElement(name = "ji")
    public String ji;
    
    @XmlElement(name = "mgmPmsrgstPk")
    public String mgmPmsrgstPk;
    
    @XmlElement(name = "bldNm")
    public String bldNm;
    
    @XmlElement(name = "splotNm")
    public String splotNm;
    
    @XmlElement(name = "block")
    public String block;
    
    @XmlElement(name = "lot")
    public String lot;
    
    @XmlElement(name = "jimokCdNm")
    public String jimokCdNm;
    
    @XmlElement(name = "jiyukCdNm")
    public String jiyukCdNm;
    
    @XmlElement(name = "guyukCdNm")    
    public String guyukCdNm;
    
    @XmlElement(name = "jimokCd")
    public String jimokCd;
    
    @XmlElement(name = "jiyukCd")
    public String jiyukCd;
    
    @XmlElement(name = "jiguCd")
    public String jiguCd;
    
    @XmlElement(name = "archGbCdNm")
    public String archGbCdNm;
    
    @XmlElement(name = "archGbCd")
    public String archGbCd;
    
    @XmlElement(name = "platArea")
    public float platArea;
    
    @XmlElement(name = "archArea")
    public float archArea;
    
    @XmlElement(name = "bcRat")
    public float bcRat;
    
    @XmlElement(name = "totArea")
    public float totArea;
    
    @XmlElement(name = "vlRatEstmTotArea")
    public float vlRatEstmTotArea;
    
    @XmlElement(name = "vlRat")
    public float vlRat;
    
    @XmlElement(name = "mainBldCnt")
    public int mainBldCnt;
    
    @XmlElement(name = "atchBldDongCnt")
    public int atchBldDongCnt;
    
    @XmlElement(name = "mainPurpsCd")
    public String mainPurpsCd;
    
    @XmlElement(name = "mainPurpsCdNm")
    public String mainPurpsCdNm;
    
    @XmlElement(name = "hhldCnt")
    public int hhldCnt;
    
    @XmlElement(name = "hoCnt")
    public int hoCnt;
    
    @XmlElement(name = "fmlyCnt")
    public int fmlyCnt;
    
    @XmlElement(name = "stcnsSchedDay")
    public String stcnsSchedDay;
    
    @XmlElement(name = "stcnsDelayDay")
    public String stcnsDelayDay;
    
    @XmlElement(name = "realStcnsDay")
    public String realStcnsDay;
    
    @XmlElement(name = "archPmsDay")
    public String archPmsDay;
    
    @XmlElement(name = "useAprDay")
    public String useAprDay;
    
    @XmlElement(name = "crtnDay")
    public String crtnDay;
    
    //------------dong-------------------------------
    
    @XmlElement(name = "mgmDongOulnPk")
    public String mgmDongOulnPk;
    
    @XmlElement(name = "mainAtchGbcd")
    public String mainAtchGbcd;
    
    @XmlElement(name = "mainAtchGbcdNm")
    public String mainAtchGbcdNm;
    
    @XmlElement(name = "strctCd")    
    public String strctCd;
    
    @XmlElement(name = "strctCdNm")    
    public String strctCdNm;
    
    @XmlElement(name = "roofCd")    
    public String roofCd;
    
    @XmlElement(name = "roofCdNm")    
    public String roofCdNm;
    
    //-----------------flr --------------------
    
    @XmlElement(name = "mgmFlrOulnPk")
    public String mgmFlrOulnPk;
    
    @XmlElement(name = "flrNo")
    public int flrNo;
    
    @XmlElement(name = "flrArea")
    public float flrArea;
    
    @XmlElement(name = "flrGbCd")
    public String flrGbCd;
    
    @XmlElement(name = "flrGbCdNm")
    public String flrGbCdNm;
    
    
    //--------------ho -----------------------
    
    @XmlElement(name = "mgmHoDetlPk")
    public String mgmHoDetlPk;
    
    @XmlElement(name = "hoNo")
    public int hoNo;
    
    @XmlElement(name = "hoNm")
    public String hoNm;
    
    @XmlElement(name = "pngTypGbNm")
    public String pngTypGbNm;
    
    @XmlElement(name = "changGbCd")
    public String changGbCd;
    
    @XmlElement(name = "changGbCdNm")    
    public String changGbCdNm;
    
}
 
728x90
반응형