BackEnd/WEB

국비_Day90

Leo.K 2022. 7. 11. 13:13

XML데이터 파싱하기 

[ drink.xml ]

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
 
<products>
    <product price="950">흰우유</product>
    <product price="90">바나나우유</product>
    <product price="1050">딸기우유</product>
    <product price="1000">초코우유</product>
    <product price="1100">메론우유</product>
</products>
cs

[ test_drink.html ]

데이터타입을 xml로 읽어오면 위의 xml파일을 읽어서 배열로 반환되어 data에 담기게 된다. 21-22행의 주석을 참고하여 파싱하는 방법을 익혀보자

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
    function result(){
        $("#result").empty();
        $.ajax({
            
            url : 'drink.xml',
            dataType:'xml',
            success : function(data){/* data는 xml파일이다. */
                var table ='<table>';
                table += '<thead>';
                table += '<tr><th>종류</th><th>가격</th></tr>';
                table += '</thead>';
                table += '<tbody style="background-color:orange">';
                
                /* $(data).find("product") -> 배열 값이다. each는 개선루프다. */
                $(data).find("product").each(function(){
                    
                    table += "tr";
                    table += "<td>" + $(this).text() + "</td><td>" + $(this).attr("price") + "</td>";
                    table += "</tr>";
                });
                
                table += '</tbody></table>'
                $("#result").append(table);
            },
            error:function(){
                alert("읽기 실패");
            }
        });
    }
</script>
</head>
<body>
<input type="button" value="결과" onclick="result();">
<div id="result"></div>
</body>
</html>
cs

[ 결과 ]

 

JSON 데이터 파싱하기

[ test_drink_JSON.jsp ]

1
2
3
4
5
6
7
8
9
<%@ page language="java" contentType="text/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
[
    {"name":"커피음료", "price":1500},
    {"name":"이온음료", "price":1700},
    {"name":"탄산음료", "price":1200},
    {"name":"음료", "price":950}
]
cs

[ test_drink_json.html ]

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
    function result(){
        $("#result").empty();
        $.ajax({
            
            url : 'drink_data_JSON.jsp',
            dataType:'json',
            success : function(data){/* data는 xml파일이다. */
                var table ='<table>';
                table += '<thead>';
                table += '<tr><th>종류</th><th>가격</th></tr>';
                table += '</thead>';
                table += '<tbody style="background-color:orange">';
                
                $.each(data, function(){
                    
                    table += "<tr>";
                    table += "<td>" + this["name"] + "</td><td>" + this["price"] + "</td>";
                    table += "</tr>";
                });
                
                table += '</tbody></table>'
                $("#result").append(table);
            },
            error:function(){
                alert("읽기 실패");
            }
        });
    }
</script>
</head>
<body>
<input type="button" value="결과" onclick="result();">
<div id="result"></div>
</body>
</html>
cs

[ 결과 ]

 

[ 기상청 정보 불러와서 파싱하기 ]

https://www.kma.go.kr/XML/weather/sfc_web_map.xml

위의 사이트를 방문하면 아래 이미지와 같이 기상청에서 제공하는 전국 날씨를 xml파일로 확인할 수 있다.

이를 ajax로 읽어와야 하는데, 기본적으로 ajax는 크로스 도메인을 지원하지 않는다. 

나의 서버에 있는 콘텐츠 데이터를 읽어오는 것을 로컬 도메인, 다른 서버에 있는 콘텐츠 데이터를 읽어오는 것을 크로스 도메인이라고 한다.

단, 콘텐츠를 제공하는 서버에서 크로스 도메인을 허용한다면, 크로스 도메인이 가능하지만 보안상의 문제로 그럴 일이 거의 없다고만 생각하자. 혹시라도 분산서버를 구축해서 크로스 도메인을 구현해야 한다면 아래 이미지의 코드를 헤더에 추가 하도록 한다.

 

[ WeatherListAction ]

크로스 도메인을 지원하지 않기 때문에 기상청에서 읽어온 데이터를 스트링으로 변환하여 가져온다.

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
package action;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.jasper.tagplugins.jstl.core.Url;
 
/**
 * Servlet implementation class WeatherListAction
 */
@WebServlet("/xml01.do")
public class WeatherListAction extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL("https://www.kma.go.kr/XML/weather/sfc_web_map.xml");
            URLConnection conn = url.openConnection();
            
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            
            String msg = "";
            while((msg = br.readLine()) != null) {
                sb.append(msg);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        response.setContentType("text/xml; charset=utf-8;");
        response.getWriter().print(sb.toString());
    }
 
}
 
 
cs

[ test_weather_xml.html ]

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
 
<script type="text/javascript">
    $(document).ready(function(){
        $("#btn1").click(function(){
            $("#result").empty();
            
            
            //ajax는 자기 서버에 있는 데이터만 읽을 수 있다. 로컬도메인. -> 크로스 도메인 불가능
            // 크로스 도메인 불가 -> 다른 서버에 있는 콘텐츠 정보를 읽어올 수 없다.
            // 단, 지원해주는 서버에서 허락하면 가능하다.
            // 로컬 도메인 -> 자신의 서버의 콘텐츠만 읽어올 수 있다.
            $.ajax({
                url : 'xml01.do',
                dataType:'xml',
                success : function(data){/* data는 xml파일이다. */
                    var table ='<table border="1"><thead><tr><th>지역</th><th>온도</th><th>상태</th></tr></thead>';
                    table += '<tbody style="background-color:orange">';
                    
                    $(data).find("local").each(function(){
                        
                        table += "<tr>";
                        table += "<td>" + $(this).text() + "</td>";
                        table += "<td>" + $(this).attr("ta") + "</td>";
                        table += "<td>" + $(this).attr("desc") + "</td>";
                        table += "</tr>";
                    });
                    
                    table += '</tbody></table>'
                    $("#result").append(table);
                },
                error:function(){
                    alert("읽기 실패");
                }
                
            });
            
        });//end-btn-click
    });
</script>
</head>
<body>
<input type="button" value="결과" id="btn1">
<div id="result"></div>
</body>
</html>
cs

[ 결과 ]