如何使用jQuery在同一XML中查找具有多个实例的标记的值

时间:2017-03-26 12:51:41

标签: jquery xml

我有以下XML文件。

<?xml version="1.0" encoding="utf-8"?>
<pdfDetails>
    <Menu menuTitle="AllTools">
        <pdf1>
            <tag>
                <title>Integrated Architecture1</title>
            </tag>
            <title>Integrated Architecture10</title>
            <description>details</description>
            <fileName>tools_selection_wizard.pdf</fileName>
            <imageName>icon_Image.png</imageName>
        </pdf1>
    </Menu>
</pdfDetails>

我想要标题&#34; Integrated Architecture10&#34; ,但当我编写代码时:

$(d).find('pdfDetails').each(function () {
    var data = $(this).find('Menu');
    //iterate over childern of Menu tag
    $(data).children().each(function(){
        var title= $(data).find('title').text();
        console.log(title);
     });
});

它输出为:

  

Integrated Architecture1Integrated Architecture10

但我只想要

  

集成架构10

我怎么能得到它?

1 个答案:

答案 0 :(得分:0)

在内部循环中,您引用data,而您应该真正引用this。由于this已引用pdf1元素,因此您只需要title集合上的children过滤器:

    var title= $(this).children('title').text();

&#13;
&#13;
var d = $.parseXML(`<?xml version="1.0" encoding="utf-8"?>
<pdfDetails>
    <Menu menuTitle="AllTools">
        <pdf1>
            <tag>
                <title>Integrated Architecture1</title>
            </tag>
            <title>Integrated Architecture10</title>
            <description>details</description>
            <fileName>tools_selection_wizard.pdf</fileName>
            <imageName>icon_Image.png</imageName>
        </pdf1>
    </Menu>
</pdfDetails>`);

$(d).find('pdfDetails').each(function () {
    var data = $(this).find('Menu');
    //iterate over childern of Menu tag
    $(data).children().each(function(){
        var title = $(this).children('title').text();
        console.log(title);
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;