개발Story

코딩테스트를 보던 중 xml형태의 문자열을 json형태로 파싱할 일이 생겼다.

 

흔히 프로젝트에서는 xml 라이브러리를 사용하면 되지만 코딩테스트를 할때는 Vanilla js를 사용하기때문에 parse하는 함수를 알아보겠다.

 

1. Parse XML to JSON

<javascript />
function parseXML (data) { var xml, tmp; if (!data || typeof data !== "string") { return null; } try { if (window.DOMParser) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString(data, "text/xml"); } else { // IE xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = "false"; xml.loadXML(data); } } catch(e) { xml = undefined; } if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { throw new Error("Invalid XML: " + data); } return xml; }

Changes XML to JSON

<javascript />
function xmlToJson(xml) { // Create the return object var obj = {}; if (xml.nodeType == 1) { // element // do attributes if (xml.attributes.length > 0) { obj["@attributes"] = {}; for (var j = 0; j < xml.attributes.length; j++) { var attribute = xml.attributes.item(j); obj["@attributes"][attribute.nodeName] = attribute.nodeValue; } } } else if (xml.nodeType == 3) { // text obj = xml.nodeValue; } // do children if (xml.hasChildNodes()) { for(var i = 0; i < xml.childNodes.length; i++) { var item = xml.childNodes.item(i); var nodeName = item.nodeName; if (typeof(obj[nodeName]) == "undefined") { obj[nodeName] = xmlToJson(item); } else { if (typeof(obj[nodeName].push) == "undefined") { var old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(xmlToJson(item)); } } } return obj; }

 

사용 예제)

<javascript />
var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<catalog>' + '<book id="bk101">' + '<author>Gambardella, Matthew</author>' + '<title>XML Developer\'s Guide</title>' + '<genre>Computer</genre>' + '<price>44.95</price>' + '<publish_date>2000-10-01</publish_date>' + '<description>An in-depth look at creating applications with XML.</description>' + '</book>' + '</catalog>'; console.log(JSON.stringify(xmlToJson(parseXML(xml))));

 

함수를 선언해주면 xml형태를 json형태로 파싱이 가능하다.

 

출처 : http://vanilla-js.blogspot.com/2016/07/parse-xml-to-json.htm

 

profile

개발Story

@슬래기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!