Saturday, 8 February 2014

Read XML Namespaces in all browser using javascript/jQuery

Developer get so many difficulties while reading XML namespaces in all browsers.
I was also one of them.

Demo XML:

<StudentRegistrationResult>
<a:StudRegistration.Details>
<a:Name>ABC</a:Name>
<a:Address>DEF</a:Address>
<a:Mobile>123</a:Mobile>
</a:StudRegistration.Details>
<a:StudRegistration.Details>
<a:Name>GHI</a:Name>
<a:Address>JKL</a:Address>
<a:Mobile>456</a:Mobile>
</a:StudRegistration.Details>
<a:StudRegistration.Details>
<a:Name>MNO</a:Name>
<a:Address>PQR</a:Address>
<a:Mobile>789</a:Mobile>
</a:StudRegistration.Details>
</StudentRegistrationResult>

call the service and get the result (refer the below link for calling the web service)

http://www.kailashtandel.com/2014/01/call-wcf-restful-service-from-cross.html

Now read the xml namespace, refer below code.

function BindStudData(StudData) {
var Name = StudData.getElementsByTagNameNS ? StudData.getElementsByTagNameNS("*", "Name") : StudData.getElementsByTagName("a:Name");

var Address = StudData.getElementsByTagNameNS ? StudData.getElementsByTagNameNS("*", "Address") : StudData.getElementsByTagName("a:Address");

var Mobile = StudData.getElementsByTagNameNS ? StudData.getElementsByTagNameNS("*", "Mobile") : StudData.getElementsByTagName("a:Mobile");

for (var i = 0; i < Name.length; i++) {
//--- Read content using following syntax
Name[i].textContent.toString();
Address[i].textContent.toString();
Mobile[i].textContent.toString();
}
}

Above code is working with all the browser IE,FF,Chrome,Opera etc.
Hope this will help you guys.
Enjoy scripting...