在Javascript中查询XML

时间:2011-10-18 15:39:53

标签: javascript html xml xquery

我不知道如何使用Javascript查询XML文件。这可能不是XML真正适合的东西(我知道一个功能齐全的数据库可能是更好的选择)。我已经研究过像XQuery这样的工具,但我不知道这是怎么回事。浏览器支持XQuery吗?我可以在Javascript文件中编写XQuery语句,以便我可以在其他javascript函数中使用结果吗?任何帮助将不胜感激 以下是一些背景信息:

$.ajax({

    url: "http://api.wunderground.com/api/test.json",
    dataType: "jsonp",
    success: function (parsed_json) {
        //do stuff with json file
    $.ajax({
        type: "GET",
        url: "weather_map.xml",
        dataType: "xml",
        success: function(xml) {
            var value = $(xml).find('condition[name="Clear"]').text();
            alert(value);
                    // do stuff with XML file
        }
    });
        //do more stuff with json file
 });

5 个答案:

答案 0 :(得分:2)

在JavaScript中处理XML的最简单方法之一是使用jQuery。这是一个非常常见的JavaScript库,可用于处理XML文件。例如

var xml = '<students><student name="bob" last="smith"/><student name="john" last="doe"/></students>';
var value = $(xml).find('student[name="bob"]').attr('last');
console.log(value);  // prints: smith

漂亮的教程:http://www.switchonthecode.com/tutorials/xml-parsing-with-jquery

答案 1 :(得分:0)

for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

答案 2 :(得分:0)

答案 3 :(得分:0)

您是否在http://xqib.org的浏览器中考虑了XQuery?

那里有一个很好的演示:http://xqueryguestbook.my28msec.com/

答案 4 :(得分:0)

E4X支持在某些浏览器中,但我不知道覆盖范围有多广。它不是xquery,但它是一种在javascript中处理xml数据的非常自然的方式。

var x=new XML("<root><el>hello, world</el></root>");
alert(x.el);

E4X的一个很好的指南是http://rephrase.net/days/07/06/e4x