Javascript: How to convert string into XML Object in Javascript ?

In JavaScript we have string which format is equivalent to XML but In actual data is not in XML so we can’t enjoy predefine function and can’t manipulate string as XML so shoot out this issue we have to first convert string into XML object so that It allow to use manipulation of content inside node easily.

Cases Where we need to consider this conversion ( String into XML Object)

-> From server In response we get XML like formatted data but in actual data type of data  is string so we can’t apply manipulation on string by using XML manipulation function.

Let’s have example: First we have declare a var xmlString of type string if we want to see the type of xmlString we can use console.log( typeof xmlString); it will return string.


var xmlString = "<userInfo>
                    <name>Nishant</name>
                    <email>mindfiresolutions@gmail.com</email>
                </userInfo>";

So We will use XML Parser to parse string into XML object to enjoy feature of XML. As all modern browser have built
in XML Parser.

Below ParseXML function will take string val and return XML object


function ParseXML(val)
{
	if (window.DOMParser)
	  {
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(val,"text/xml");
	  }
	else // Internet Explorer
	  {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.loadXML(val);
	  }
return xmlDoc ;
}

After converting string into XML object we can enjoy XML manipulation

var xmlDataObj = ParseXML(xmlString);
console.log(xmlDataObj.getElementsByTagName('name')[0].childNodes[0].nodeValue)

Output will be Nishant

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s