如何从Iframe获取XML

时间:2012-01-05 14:30:17

标签: javascript jquery xml-parsing

我有一个包含XML字符串的iframe。我想提取它,以便在javascript或jquery中进行处理。 以下是iframe样本

<iframe>
    <list>
        <request>
            <name>CourseDaoMarklogicImpl</name>
            <id>spring735cfdc6d848026363b835bfcc69c5026a56d217</id>
            <hits>21</hits>
            <durationsSum>3438</durationsSum>
            <durationsSquareSum>1481952</durationsSquareSum>
            <maximum>688</maximum>
            <cpuTimeSum>45</cpuTimeSum>
            <systemErrors>0</systemErrors>
            <responseSizesSum>-21</responseSizesSum>
            <childHits>0</childHits>
            <childDurationsSum>0</childDurationsSum>
        </request>
    </list>
</iframe>

有没有办法做到这一点?感谢

3 个答案:

答案 0 :(得分:1)

$('<div>').append(  $(".iframe").contents()    ).remove().text()

修改

我现在已经看到它是跨域的。

这不会起作用

你应该使用jSonP。

答案 1 :(得分:1)

如果是相同的域名:

alert($("<div>").append($("list", frames['nameOfMyIframe'].document)).html())

答案 2 :(得分:0)

试试这个:

// get the content of iframe and parse it to a jQuery object
var xml = $($("iframe").text());
// find a 'name' element and retrieve the text
xml.find('name').text(); // "CourseDaoMarklogicImpl"

更新

如果是跨域,则必须以不同方式检索数据。您可以使用YQL服务。

var url = ""; // url to your XML file

$.ajax({
  url: "http://query.yahooapis.com/v1/public/yql",
  data: {
    q: "select * from xml where url='" + url + "'",
    format: "json"
  }, 
  success: function(data) {
    console.log(data); // data is a Object representing XML data
  }
});

HERE 就是一个例子。