Search code examples
javascriptxmlnodesgetelementsbytagname

Access XML data via javascript


How can I get the value of my xml data using a javascript. Im accessing my xml file on my domain, and view it on the client side.

my.xml

<usr>
  <uid trk="1234">
    <getThis>kdzbnya</getThis>
  </uid>
</usr>

I want to get the value of "getThis"

sample.js

function alertThis(){
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        var xmlFile = "my.xml";
        xmlDoc.async="false";
        xmlDoc.load(xmlFile);
        xmlObj=xmlDoc.documentElement;
        try {
            var v = "";
            $.each(xmlObj.childNodes, function(i, valThis) { 
                if(valThis.getAttribute("trk") == "1234"){
                    v += valThis.getElementsByTagName('getThis').nodeValue;
                }   
            });
             alert(v);
        }
        catch(e){
            alert(e);
        }
}

but it returns undefined value.


Solution

  • I see you're using jQuery.

    change

    v += valThis.getElementsByTagName('getThis').nodeValue
    

    to

    v += $(valThis).find('getThis').text()