Why is this JavaScript code giving me an "undefined" error?

I also tried to use Microsoft's loadXML () but it doesn't work. This is most likely not recommended. What seems to be wrong here. Is there any other way to write it?

HTML code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <title>childNode Property</title>
        <script type="text/javascript" src="allfeaturetest.js"></script>
    </head>
    <body>
        <h1>childNode Property</h1>
        <hr/>
        <form name="input">
            <input type="button" value="Press me for XML" onclick="return xmlly()"/>
        </form>
        <div id="pop">
        </div>
    </body>
</html>

      

JavaScript code:

function xmlly(){
    var resul ="";
    var dom = new DOMParser();
    var xmlDoc = dom.parseFromString("address.xml","application/xml");
    var myElem = xmlDoc.getElementsByTagName("address").childNodes;
    alert(myElem); //gives me undefined
    alert(xmlDoc); //gives me [Object XMLDocument]
    document.getElementById("pop").innerHTML = xmlDoc.documentElement.childNodes[0].attributes[0].nodeValue;
}

      

XML file:

<address>
 <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
 </address>

      

The error shown to me:

Uncaught TypeError: Cannot read property 'nodeValue' of undefined

+3


source to share


2 answers


parseFromString

will not load data from a file address.xml

. As the name says, it will parse an XML document from a string only , for example:

var dom = new DOMParser();
var xmlDoc = dom.parseFromString("<address>test</address>","application/xml");

      



You will need a separate XHR (Ajax) request to load data from this file.

Also, you should use console.log

instead alert

to debug it. You will be able to see what is in this object (error message in your case).

+2


source


If your only goal is to read node then use below functions -



function xmlly()
{
var xmlDoc=loadXMLDoc("address.xml");
var elm  = xmlDoc.getElementsByTagName("street")[0]; // tag name you want to read
var node =elm.childNodes[0];
alert(node.nodeValue)
}

function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else // code for IE5 and IE6
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}

      

0


source







All Articles