Javascript XML加载jQuery

时间:2014-02-19 17:39:40

标签: javascript jquery xml

我在使用jQuery将XML数据加载到javascript时遇到了问题。

我这里有一个xml:

<config>
<device>
    <node>1</node>
    <name>Block</name>
    <description>Block in saloon</description>
    <area>Salon</area>
</device>   
<device>
    <node>2</node>
    <name>Line</name>
    <description>Lottr</description>
    <area>Living room</area>
</device>   
</config>   

我想找到node = 2的设备名称。

这是我的代码:

       $.ajax({
         type: "GET",
         url: "config2.xml",
         dataType: "xml",
         success: function(xml) {
            var kurs = $(xml).find('name').text();
            alert(kurs);
         }
   });

我应该把什么放入var kurs?

3 个答案:

答案 0 :(得分:0)

var myVal;
$(xml).find('node').each(  //find the node and loop through them
    function(){
        var node = $(this);  
        if (node.text==="2") {   //see if the node's value is 2
            myVal = node.siblings("name").text();  //find the sibling name element
            return false;  //exit the each loop
        }
    }
);
console.log(myVal);

答案 1 :(得分:0)

与此问题类似:jQuery to get matching nodes in XML

我认为这样的事情应该有效:

$.ajax({
     type: "GET",
     url: "config2.xml",
     dataType: "xml",
     success: function(xml) {
        //this should get you the device node 
        var $kurs = $(xml).find('node:contains("2")').parent();
        //this should get you the name from the device node
        var name = $kurs.find('name'); 
     }
}); 

答案 2 :(得分:0)

$(document).ready(function () {

  $.ajax({
    type: "GET",
    url: "config2.xml",
    dataType: "xml",
    success: function (xml) {
      $(xml).find('device').each(function () {
        var node = $(this).find('node');

        if (node.text() == '2') {
          name = $(this).find('name').text();
        }

      });
    }
  });

});