Parsing XML


Hi everyone . To day i will introduce about parsing XML form server response for client. We will use js to process it.

Note :
-How to treat the Ajax response as XML

  • var xmlDoc = response.responseXML;

How to get an array of subelements

  • xmlDoc.getElementsByTagName(…)

-How to get an attribute of an element

  • someElement.getAttribute(…)

-How to get the body content of an e lement

  • someElement.firstChild.nodeValue

– The top-level element

  • xmlDoc.documentElement (and …nodeName)

– An element’s main tag name

  • someElement.nodeName

– All attributes of an element

  • someElement.attributes

– Child nodes of an element

  • someElement.childNodes

Summary of Main Classes:

  • Document class

Properties

  • documentElement

Methods

  • getElementsByTagName, getElementById (HTML only )
  • Element class

Methods

  • getAttribute, getElementsByTagName, hasAttribute
  • Node

Properties

  • attributes, childNodes, firstChild, lastChild, nextSibling, nodeName, nodeType, nodeValue, parentNode, previousSibling

Methods

  • hasAttributes, hasChildNodes, normalize

We have the file js when server respone to client:

</pre>
// Server response for client.
var test =
"<customers rating='vip'>" +
 "<customer id= 'a1234 '>" +
 "<firstName>Rafael</firstName>" +
 "<lastName>Nadal</lastName>" +
 "</customer>" +
 "<customer id='a1235'>" +
 "<firstName>Roger</firstName>" +
 "<lastName>Federer</lastName>" +
 "</customer> " +
"</customers>";

&nbsp;

function getXmlDoc(xmlString) {
 var parser = new DOMParser();
 var xmlDocument =
 parser.parseFromString(xmlString, "application/xml");
 return(xmlDocument);
}

var testDoc = getXmlDoc(test);

testDoc.documentElement.nodeName;
testDoc.documentElement.getAttribute("rating");

testDoc.getElementsByTagName("lastName")[1].firstChild.nodeValue;

var rafie = testDoc.getElementsByTagName("customer")[0];
rafie.getAttribute("id");
testDoc.getElementById("a1234");
<pre>

OK . We can test it…..Good luck to you.

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

%d bloggers like this: