使用JQuery通过Value检查XML节点是否存在

时间:2009-09-17 02:18:51

标签: jquery xml search

我正在尝试使用Jquery检查xml节点中是否存在值。 xml字符串是:

        <SectionAnswers>
            <SectionAnswer>
                <detailID>2216</detailID>
                <SourceAnswerID>979</SourceAnswerID>
            </SectionAnswer>
            <SectionAnswer>
                <detailID>2218</detailID>
                <SourceAnswerID>981</SourceAnswerID>
            </SectionAnswer>
            <SectionAnswer>
                <detailID>2219</detailID>
                <SourceAnswerID>977</SourceAnswerID>
            </SectionAnswer>
            <SectionAnswer>
                <detailID>2221</detailID>
                <SourceAnswerID>980</SourceAnswerID>
            </SectionAnswer>
            <SectionAnswer>
                <detailID>2282</detailID>
                <SourceAnswerID>64</SourceAnswerID>
            </SectionAnswer>
            <SectionAnswer>
                <detailID>2283</detailID>
                <SourceAnswerID>978</SourceAnswerID>
            </SectionAnswer>
            <SectionAnswer>
                <detailID>2596</detailID>
                <SourceAnswerID>73</SourceAnswerID>
            </SectionAnswer>
        </SectionAnswers>

当我尝试使用以下内容查询值时:

$(“SectionAnswers”,Section).find(“64”)// Section是jquery上下文

我收到以下回复:

Expression不会返回DOM节点。

.//--& GT; 64&LT; -

我出错的任何想法?我真的不想循环检查每次检查值,如$(“SectionAnswers”,Section).each()

由于

4 个答案:

答案 0 :(得分:4)

尝试使用简单的$ .each遍历XML:

$('SectionAnswers > SectionAnswer').each(function() {
    if($(this).find('SourceAnswerID').text() == '64') {
        alert('Found 64 at detailID: ' + $(this).find('detailID').text());
    }
});

或使用filter

var $sa = $('SectionAnswers > SectionAnswer').filter(function() {
    return $(this).find('SourceAnswerID').text() == '64'; 
});
alert($sa.find('SourceAnswerID').text());
alert($sa.find('detailID').text());

答案 1 :(得分:1)

我将此处留在此处作为参考,因为它可能在稍微不同的情况下有用,但是,就像karim79提到的那样,它匹配任何有64作为子串的东西。


您应该可以使用":contains(text)" pseudo-selector

$("SectionAnswers SourceAnswerID:contains('64')", Section)

这将选择SourceAnswerID元素,因此您可能需要使用parent()closest()函数向上移动层次结构。

答案 2 :(得分:0)

谢谢你们。

我会玩这两个,看看我能想出什么。我希望尽可能避免循环,因为它已经在循环内运行了,我只有一个关于嵌套循环的按钮......

但是现在我想到了......过滤器和包含调用都是内部循环...所以它实际上可能表现得更好,只需简单地获取集合并迭代它。

答案 3 :(得分:0)

好的修复了。我最终更改了xml以生成ID属性,因此它是

        <SectionAnswers>
            <SectionAnswer SourceAnswerID="1487"
                           detailID="1420" />
            <SectionAnswer SourceAnswerID="1488"
                           detailID="2039" />
        </SectionAnswers>

我现在可以通过

找到它

查找( “SectionAnswer [SourceAnswerID = 1487]”)

无论如何,这是一个更好的解决方案,因为将信息放入属性会减少返回值的大小。