如何使用jQuery在XML树中获取特定节点

时间:2021-01-05 14:00:55

I have the following XML file:

我有以下XML文件:

<?xml version="1.0" encoding="iso-8859-1"?>
<words>
    <word>
        <id>1</id>
        <name>Teacher</name>
    </word>
    <word>
        <id>2</id>
        <name>Pitcher</name>
    </word>
</words>

And the following jQuery code:

以下是jQuery代码:

$.ajax({
    type: "GET",
    url: "sites.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('word').each(function(){

        ...

});

How can I get word with ID == 1?

如何获得ID为== 1的单词?

This ajax function is inside another function (getWord() function). I want to get word with any ID and assign that value to a local variable of getWord() function.

这个ajax函数在另一个函数内(getWord()函数)。我希望得到任何ID的单词并将该值赋给getWord()函数的局部变量。

How can I do that?

我怎样才能做到这一点?

2 个解决方案

#1


3  

You can always resort to writing a custom filter.

您始终可以编写自定义过滤器。

$(xml).find("word").filter(function () {
  return $(this).find("id").text() == "1";
}).each(function () {
  console.log(this);
});

#2


1  

$(xml).find('word').each(function(){

       if(parseInt($(this).find('id').text()) == '1')
{

      // your logic here
}
});

#1


3  

You can always resort to writing a custom filter.

您始终可以编写自定义过滤器。

$(xml).find("word").filter(function () {
  return $(this).find("id").text() == "1";
}).each(function () {
  console.log(this);
});

#2


1  

$(xml).find('word').each(function(){

       if(parseInt($(this).find('id').text()) == '1')
{

      // your logic here
}
});