Access XML data via javascript

泪湿孤枕 提交于 2019-12-11 23:59:03

问题


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.


回答1:


I see you're using jQuery.

change

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

to

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



回答2:


Try adding a .item(0) or [0] between getElementsByTagName(...) and .nodeValue:

v += valThis.getElementsByTagName('getThis').item(0).nodeValue;

You'll need this as getElementsByTagName returns a NodeList (which can resemble an Array). The list won't have a nodeValue property itself, but the nodes within it should.




回答3:


See this example http://www.w3schools.com/xml/xml_parser.asp of an XML parser. But in reality you probably want to use a framework to load the XML and parse it. There is plenty of them out there, check microjs.com for the features that you are looking for.



来源:https://stackoverflow.com/questions/8844385/access-xml-data-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!