asprin
asprin

Reputation: 9833

XML Parsing not Working in Chrome

For an XML string such as:

var xml_string = '<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">   <env:Header/>   <env:Body>      <dn:response id="?" xmlns:dn="http://www.datanomic.com/ws">         <dn:record>            <dn:Result>John</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johnghghg</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johnn</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johnngy</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johnnnn</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johnny</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johns</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johnson</dn:Result>         </dn:record>         <dn:record>            <dn:Result>Johnston</dn:Result>         </dn:record>      </dn:response>   </env:Body></env:Envelope>';

I'm using the following code (obtained from SO itself)

if (window.DOMParser)
  {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(xml_string,"text/xml");
  }
else // Internet Explorer
  {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.loadXML(xml_string);
  }
  var nodes = xmlDoc.getElementsByTagName("dn:Result");
  console.log(nodes); // returning empty on Chrome, working fine in Firefox and IE10

If I remove the dn: from getElementsByTagName, it starts to work in Chrome but not in Firefox and IE. So is there a solution for it to work in all 3 browsers?

Here is the fiddle for ease of testing: JSFiddle

PS: jQuery isn't an option. I'm hoping this could be done via plain old Javascript alone.

Upvotes: 1

Views: 2573

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

I would suggest to use the W3C DOM Level 2 method getElementsByTagNameNS where available, see http://jsfiddle.net/bygx406g/, which changes one line to

var nodes = typeof xmlDoc.getElementsByTagNameNS != 'undefined' ? xmlDoc.getElementsByTagNameNS('http://www.datanomic.com/ws', 'Result') : xmlDoc.getElementsByTagName("dn:Result");

Upvotes: 3

Related Questions