使用过滤进行XML解析

时间:2016-03-23 18:36:11

标签: jquery html xml

我的XML文件看起来像这样 -

 <?xml version="1.0" encoding="UTF-8"?>
    <prj:Flow xmlns:prj="url1" xmlns:com="url2" xmlns:ns2="url3" xmlns:con="url4" xmlns:ns0="url5" xmlns:ns1="url6" xmlns:ns3="url7">
    <prj:str>
    <prj:layout comp="abcd">
      <prj:prop>
         <prj:property name="Hardik" value="5000"/>
      </prj:prop>
    <prj:look>
      <prj:lite name="bajaj">
      <prj:lite name="honda">
    </prj:look>
    </prj:layout>
<prj:layout comp="efgh">
      <prj:prop>
         <prj:property name="Vipul" value="6000"/>
      </prj:prop>
    <prj:look>
      <prj:lite name="yamaha">
      <prj:lite name="honda">
    </prj:look>
    </prj:layout>
    </prj:str>
    </prj:Flow>

我需要解析这个XML,以便我可以根据comp值检索子节点,即如果comp =“abcd”那么我应该在我的html表中显示bajaj和honda。今天,我的解析器显示所有属性,而不管用于过滤的comp值。任何帮助都非常感谢。

我的解析器 -

$.ajax({
    type: "GET",
    url: 'sample.xml',
    dataType: "xml",
    success: function(xml) {
       var compname = $(xml).find("prj\\:layout,layout").attr('comp');
       if(compname == "abcd") {
          $(xml).find("prj\\:look, look").each(function() {
            var $entry = $(this);
            var pic = $entry.find("prj\\:lite,lite").each(function() {
              var name = $(this).attr('name');
              $('<tr></tr>').html('<td>' + name + '</td>').appendTo('#listnames');
        })
      })
    }
}  
  })

1 个答案:

答案 0 :(得分:1)

问题

获得所有属性的原因是你的var compname声明不在循环中。现在你问:从所有布局中,给我一个名为comp的属性。由于.attr()将返回第一个匹配的属性,因此将始终返回&#39; abcd&#39;。所以当你检查compname =&#34; abcd&#34;它总是如此。

可能的解决方案

你可以循环布局。然后在该循​​环内检查当前布局的compname属性是什么。然后检查它是否与您的目标compname匹配。其余的代码工作正常。

$.ajax({
  type: "GET",
  url: 'sample.xml',
  dataType: "xml",
  success: function(xml) {

    //First find the layouts
    var layouts = $(xml).find("prj\\:layout,layout");

    //Loop through the layouts
    layouts.each(function(){

      //Get this layout comp attribute
      var compname = $(this).attr('comp');

      //check if the comp is our target comp
      if(compname == "abcd") {
        var $entry = $(this);

        //Loop the 'lite' elements
        var pic = $entry.find("prj\\:lite,lite").each(function() {
          var name = $(this).attr('name');

          //Log for testing (remove in production)
          console.log("found " + name);

          //Your magic
          $('<tr></tr>').html('<td>' + name + '</td>').appendTo('#listnames');

        })
      }
    })

  }  
})

更有效的解决方案

您还可以通过立即获得正确的精简元素的方式构建选择器

$.ajax({
  type: "GET",
  url: 'sample.xml',
  dataType: "xml",
  success: function(xml) {

    //Find the entries
    var $entries = $(xml).find("prj\\:layout[comp='abcd'] prj\\:lite");

    //Loop the entries
    $entries.each(function() {
      var name = $(this).attr('name');

      //Log for testing (remove in production)
      console.log("found " + name);

      //Your magic
      $('<tr></tr>').html('<td>' + name + '</td>').appendTo('#listnames');

    })

  }  
})