在jQuery中获取xml子节点的属性

时间:2016-08-01 19:22:01

标签: jquery xml attr

我不得不修改这个问题,因为我遗漏了一段破坏事物的代码。我只想看看某个教会的图像。

xml文件:

<churches>
<church>
        <data-name>germanevangelical</data-name>
        <name>German Evangelical</name>
        <address>501 Elm St.</address>
        <opened>1887</opened>
        <neighborhood>East</neighborhood>
        <region>East</region>
        <architecture>Gothic</architecture>
        <denomination>Evangelical Lutheran</denomination>
        <closed>2006</closed>
        <image caption="Mary Smith">image_1_forweb.jpg</image>
        <image caption="Mary Smith">image_2_forweb.jpg</image>
        <image caption="Mary Smith">image_3_forweb.jpg</image>
</church>
... (more church nodes)
</churches>

我想用jQuery访问图片标题。

这是我的代码,但它为字幕返回“undefined”:

var cName = 'germanevangelical';  
$.ajax({
              type: "GET",
              url: "churchdata.xml",
              dataType: "xml",
              success: function(xml) {
                var name = $(xml).find("data-name"); //get church names from xml file
                $(name).each(function(id, item) {
                    if ($(item).text() == cName) { //find the right church in the xml file
                        $(item).parent().find("image").each(function(id, node) {
                            console.log('id: ' + $(node).attr('caption'));//undefined
                        })
                    }//end if right church in xml file
                })
              }
            });

有人能看到我做错了吗?

2 个答案:

答案 0 :(得分:0)

解析时,ajax代码中存在一个非常小的错误,在查找“data-name”时使用$ xml而不是$(xml)。请检查以下代码。尝试在chrome中运行您的页面并检查开发人员工具中是否有任何错误,如果有任何错误,它将无法正常工作。

var cName = 'germanevangelical';  
$.ajax({
type: "GET",
    url: "churchdata.xml",
    dataType: "xml",
    success: function (xml) {
    var xmlDoc = $.parseXML(xml),
    $xml = $(xmlDoc);
    var name = $xml.find("data-name"); //get church names from xml file
        $(name).each(function(id,item) {
              if ($(item).text() == cName) {
                $(item).parent().find("image").each(function(id,node) { 
                    console.log('id: ' + $(node).attr('caption')); //undefined
                });
               }
        });
      }
 });

答案 1 :(得分:0)

$.parseXML()不是必需的,dataType的{​​{1}}设置为$.ajax()"xml"应该XMLDocument返回xml success 1 {} $.ajax()来电。

另请注意,在问题)处的.each()来电时错过了javascript。{/ p>

$.ajax({
  type: "GET",
  url: "churchdata.xml",
  dataType: "xml",
  success: function(xml) {
    console.log(xml);
    var name = $(xml).find("data-name"); //get church names from xml file
    $(name).each(function(id, item) {
      $(item).parent().find("image").each(function(id, node) {
        console.log('id: ' + $(node).attr('caption'));
      })
    })
  }
});

plnkr http://plnkr.co/edit/HYaaxN0EY0JtkciBMJpl?p=preview