IT정보사전

[JAVA] API데이터 XML파싱(Parsing) 방법 본문

웹 프로그래밍

[JAVA] API데이터 XML파싱(Parsing) 방법

작은나무0530 2019. 9. 20. 15:03
728x90
반응형

안녕하세요~ 작은나무입니다!!
요즘 프로젝트 진행하면서 REST API방식으로 데이터를 많이 받아오는대요~
많이들 사용하는 JSON DATA의 경우는 많이 접해봤는대... 이번에 XML DATA를 받아서 파싱(Parsing)하는 프로젝트가 있어서 간단하게 정리해 보도록 하겠습니다.

[소스구현 - Class]

public class XmlParserUtil {
    public static Map<String, Object> XmlToMap(String xml) throws SAXException, IOException, ParserConfigurationException {
        Map<String, Object> msgMap = new HashMap<String, Object>();
        
        //XML파싱(Parsing)
        InputSource is = new InputSource(new StringReader(new String(xml)));
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
        document.getDocumentElement().normalize(); // optional, but recommended
        NodeList nodeList = null;
        ArrayList<Map<String, String>> xmlList = new ArrayList<Map<String, String>>();
        String getNodeName = "";
        
        // root 다음의 첫번째 노드 명
        if(document.getFirstChild().getChildNodes().getLength() > 0){
            getNodeName = document.getFirstChild().getFirstChild().getNodeName();
            
            // root 다음의 첫번째 노드 찾아서 셋팅
            nodeList = document.getElementsByTagName(getNodeName);
            
            for (int i = 0; i < nodeList.getLength(); i++) {
                // nodeList의 Child Node를 다시 nodeList에 셋팅
                NodeList childList = nodeList.item(i).getChildNodes();
                
                // Child Node의 key, value를 map에 순차적으로 셋팅
                Map<String, String> childNodeMap = new HashMap<String, String>();
                for (int j = 0; j < childList.getLength(); j++) {
                    String childnodename = childList.item(j).getNodeName();
                    String childnodevalue = childList.item(j).getTextContent();
                    
                    childNodeMap.put(childnodename, childnodevalue);
                }
                xmlList.add(childNodeMap);
            }
            msgMap.put("resultMap", xmlList);
        }else{
            msgMap.put("resultMap", null);
        }
        return msgMap;
    }
}

위처럼 별도로 Class를 생성하고. 호출하여 사용하면 됩니다. 아래와 같이 검증 하시면 될 것 같습니다.
예) XmlParserUtil.XmlToMap(new String(out.toByteArray(), "utf-8"));

감사합니다.

728x90
반응형
그리드형
Comments