加载XML获取特定ID的内容jQuery或Javascript

时间:2011-12-29 19:44:51

标签: jquery xml parsing load

我正在尝试解析XML Feed,然后只抓取一个特定ID及其中的内容。我只需要用JS做这个......

我尝试了各种各样的方法,没有运气。我得到的最接近的是:

var html = $("#dangericon").html();
$("#test").append( html );

但是,当我尝试首先加载xml时,这对我不起作用。它必须位于页面中...请参阅:http://jsfiddle.net/BZDBF/5/

我试过了: 然而,.ajax,.load和.parseXML()由于XML格式不正确而无法正常工作......

我的xml链接是:http://www.sierraavalanchecenter.org/bottomline-rss.php 我想获得#dangericon内容,即图像。

谢谢大家。

1 个答案:

答案 0 :(得分:0)

//parse the XML string (wherever it comes from), then find all the `item` tags and select their child `description` tags, now we have all the `description` tags in your XML document
var $xml_parsed = $($.parseXML(xml_string)).find('item').children('description');

//now iterate through the `description` tags and find the `#dangericon` element within each
for (var i = 0, len = $xml_parsed.length; i < len; i++) {

    //to find an element we must create a jQuery object from the text of this `description` tag and then we can use `.find()` to search for the desired element
    var tmp = $($xml_parsed.eq(i).text()).find('#dangericon');

    //you can do what you want with the element now, it is saved in the `tmp` variable
}

以下是演示:http://jsfiddle.net/pdT8S/

我假设这是在同一个域上完成的,如果是这种情况那么你不需要弄乱jsonp但是如果你跨域调用你的XML文档那么您将需要查看jsonp请求(只要远程服务器设置正确,就可以使用jQuery轻松完成)。

P.S。我是特拉基的本地人,我愿意帮助您正在开展的任何以滑雪为中心的网站。