본문 바로가기

Developer

Javascript, JQuery Xml Parsing (File, String) [Convert string to xml]

 

javascript 혹은 jquery를 이용하여 xml 문서를 만드는 방법에 대해서 알아보도록 하겠습니다.

방법은 간단하며, javascript로 생성 시 xml selector에 대해서는 이번 시간에 설명하지 않도록 하겠습니다.

 

xml document

<?xml version="1.0" encoding="utf-8" ?>
<Nodes>
	<Node Title="Collaboration Home" Url="/" ID="18295af4-d049-40ce-a7ed-e7fdafbbff82" ParentID="" Prefix="" SiteID="81ds4s67-0509-41a1-a46c-0fc6ae94490c" />
	<Node Title="tt" Url="/tt" ID="2c62624f-07fc-44a3-3617-es67c57448e" ParentID="18295af7-d049-40ce-a7ed-e7fdafbbff82" Prefix="tt" SiteID="81s04e67-0509-41a1-a46c-0fc6ae94490c" />
	<Node Title="PI/IT Home" Url="/cc/cio" ID="5318f72b-b3b6-4cab-924d-90e0c9d7addf" ParentID="" Prefix="cc" SiteID="a1asc33b-bbfd-4285-8963-949f653eb7dd" />
	<Node Title="CIO Office Only" Url="/cc/cio/cioonly" ID="e021d10e-8592-4fa6-8e00-33fc7beas384" ParentID="53e8s72b-b3b6-4cab-924d-90e0c9d7addf" Prefix="cc" SiteID="a1aac33b-sbfd-4285-8963-949f653eb7dd" />
</Nodes>

 

Script

$(document).ready(function() {
	// Jquery call .get Method
	$.get("noname1.xml", function(xml){
		xmlString = xml;
	});

	// JQuery call ajax
	$.ajax({
		type: "get"
		,url:"noname1.xml"
		,dataType: "xml"
		,async: false
		,success: function(xml, isSuccess){
			alert(xml);
			alert(isSuccess);
		}
		,error: function(data, status, err) {
			//alert("data ==> " + data);
			alert("status ==> " + status);
			//alert("err ==> " + err);
		}
	});

	// xml document parsing by file
	try{
		var xmlhttp;
		if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}

		xmlhttp.open("GET","noname1.xml",false);
		xmlhttp.send();
		xmlDoc = xmlhttp.responseXML;

		var node = xmlDoc.getElementsByTagNames("Node");
		alert(node.length);
	}
	catch(ex){
		//alert(ex.message);
	}

	// xml document parsing by string
	try{
		if (window.DOMParser){
			parser = new DOMParser();
			xmlDoc = parser.parseFromString(xmlString,"text/xml");
		}
		else{// Internet Explorer
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = false;
			xmlDoc.validateOnParse = false;
			xmlDoc.resolveExternals = false;
			ret = xmlDoc.loadXML(xmlString);

			if(!ret){
				alert(xmlDoc.parseError.reason);
				return false;
			}
		}
	}
	catch(ex){
		//alert(ex.message);
	}
		
	// Jquery
	$(xmlDoc).find("Node").each(function(){
		alert($(this).attr("Title"));
		return false;
	});

	// Javascript
	var nodes = xmlDoc.getElementsByTagName("Node");
	for(var x = 0; x < nodes.length; x++){
		alert(nodes[x].getAttribute("Title"));
		return false;
	}
});

 

 

감사합니다.