Wednesday, January 12, 2011

Javascript getElementByTagName XML with namespace prefix

How to use Javascript to retrieve XML data with namespace prefix?

Example:-



We can use getElementByTagName together with namespace prefix to access the element value:-
xmlDoc.getElementsByTagName("ns0:POID")[0].firstChild.nodeValue ;

Whole code to access the XML data with namespace prefix via getElementsByTagName:-


<html><head>

<script language="javascript">

function getXML()

{

var xmlstring = "<?xml version='1.0' ?><ns0:PO xmlns:ns0='http://www.abc.com/PO'><ns0:POID>PO123</ns0:POID><ns0:CustomerID>ABC007</ns0:CustomerID></ns0:PO>";

if (window.DOMParser)

  {

  parser=new DOMParser();

  xmlDoc=parser.parseFromString(xmlstring,"text/xml");

  }

else // Internet Explorer

  {

  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

  xmlDoc.async="false";

  xmlDoc.loadXML(xmlstring);

  }

var x = xmlDoc.getElementsByTagName("ns0:POID")[0].firstChild.nodeValue ;

alert(x);

}

</script>

</head><body onload="javascript:getXML()">

</body></html>

<?xml version='1.0' ?>
<ns0:PO xmlns:ns0='http://www.abc.com/PO'>
<ns0:POID>PO123</ns0:POID>
<ns0:CustomerID>ABC007</ns0:CustomerID>
</ns0:PO>