简体   繁体   English

使用Java Script从URL解析XML / RSS

[英]Parsing XML / RSS from URL using Java Script

Hi i want to parse xml/rss from a live url like http://rss.news.yahoo.com/rss/entertainment using pure Java Script(not jquery). 您好我想使用纯Java脚本(而不是jquery)从http://rss.news.yahoo.com/rss/entertainment等实时网址解析xml / rss。 I have googled a lot. 我google了很多。 Nothing worked for me. 没有什么对我有用。 can any one help with a working piece of code. 任何人都可以帮助处理一段代码。

(You cannot have googled a lot.) Once you have worked around the Same Origin Policy , and if the resource is served with an XML MIME type (which it is in this case , text/xml ), you can do the following: (您不能搜索很多内容。)一旦您解决了同源策略 ,并且资源以XML MIME类型在本例中为text/xml )提供,您可以执行以下操作:

var x = new XMLHttpRequest();
x.open("GET", "http://feed.example/", true);
x.onreadystatechange = function () {
  if (x.readyState == 4 && x.status == 200)
  {
    var doc = x.responseXML;
    // …
  }
};
x.send(null);

(See also AJAX , and the XMLHttpRequest Level 2 specification [Working Draft] for other event-handler properties.) (另请参阅AJAX ,以及其他事件处理程序属性的XMLHttpRequest Level 2规范[Working Draft]。)

In essence: No parsing necessary. 实质上: 不需要解析。 If you then want to access the XML data, use the standard DOM Level 2+ Core or DOM Level 3 XPath methods, eg 如果您想访问XML数据,请使用标准DOM Level 2+ CoreDOM Level 3 XPath方法,例如

/* DOM Level 2 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].firstChild.nodeValue;

/* DOM Level 3 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].textContent;

/* DOM Level 3 XPath (not using namespaces) */
var title = doc.evaluate('//channel/title/text()', doc, null, 0, null).iterateNext();

/* DOM Level 3 XPath (using namespaces) */
var namespaceResolver = (function () {
  var prefixMap = {
    media: "http://search.yahoo.com/mrss/",
    ynews: "http://news.yahoo.com/rss/"
  };

  return function (prefix) {
    return prefixMap[prefix] || null;
  };
}());

var url = doc.evaluate('//media:content/@url', doc, namespaceResolver, 0, null).iterateNext();

(See also JSX:xpath.js for a convenient, namespace-aware DOM 3 XPath wrapper that does not use jQuery.) (另请参阅JSX:xpath.js以获取不使用jQuery的方便的,名称空间感知的DOM 3 XPath包装器。)

However, if for some (wrong) reason the MIME type is not an XML MIME type, or if it is not recognized by the DOM implementation as such, you can use one of the parsers built into recent browsers to parse the responseText property value. 但是,如果由于某些(错误的)原因,MIME类型不是XML MIME类型,或者DOM实现无法识别它,则可以使用最近浏览器中内置的解析器之一来解析responseText属性值。 See pradeek's answer for a solution that works in IE/MSXML. 请参阅pradeek的答案 ,了解适用于IE / MSXML的解决方案。 The following should work everywhere else: 以下应该适用于其他地方:

var parser = new DOMParser();
var doc = parser.parseFromString(x.responseText, "text/xml");

Proceed as described above. 按上述步骤进行。

Use feature tests at runtime to determine the correct code branch for a given implementation. 在运行时使用功能测试来确定给定实现的正确代码分支。 The simplest way is: 最简单的方法是:

if (typeof DOMParser != "undefined")
{
  var parser = new DOMParser();
  // …
}
else if (typeof ActiveXObject != "undefined")
{
  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  // …
}

See also DOMParser and HTML5: DOM Parsing and Serialization (Working Draft) . 另请参见DOMParserHTML5:DOM解析和序列化(工作草案)

One big problem you might run into is that generally, you cannot get data cross domain. 您可能遇到的一个大问题是,通常情况下,您无法获取跨域数据。 This is big issue with most rss feeds. 这是大多数rss feed的大问题。

The common way to deal with loading data in javascript cross domain is calls JSONP. 处理在javascript跨域中加载数据的常用方法是调用JSONP。 Basically, this means that the data you are retrieving is wrapped in a javascript callback function. 基本上,这意味着您要检索的数据包含在javascript回调函数中。 You load the url with a script tag, and you define the function in your code. 您使用脚本标记加载URL,然后在代码中定义该函数。 So when the script loads, it executes the function and passes the data to it as an argument. 因此,当脚本加载时,它会执行该函数并将数据作为参数传递给它。

The problem with most xml/rss feeds is that services that only provide xml tend not to provide JSONP wrapping capability. 大多数xml / rss提要的问题是仅提供xml的服务往往不提供JSONP包装功能。

Before you go any farther, check to see if your data source provides a json format and JSONP functionality. 在进一步研究之前,请检查您的数据源是否提供json格式和JSONP功能。 That will make this a lot easier. 这将使这更容易。

Now, if your data source doesn't provide json and jsonp functionality, you have to get creative. 现在,如果您的数据源提供json和jsonp功能,则必须具有创造性。

On relatively easy way to handle this is to use a proxy server. 处理此问题的相对简单方法是使用代理服务器。 Your proxy runs somewhere under your control, and acts as a middleman to get your data. 您的代理在您控制的某个地方运行,并充当中间人以获取您的数据。 The server loads your xml, and then your javascript does the requests to it instead. 服务器加载你的xml,然后你的javascript代替它做请求。 If the proxy server runs on the same domain name then you can just use standard xhr(ajax) requests and you don't have to worry about cross-domain stuff. 如果代理服务器运行在相同的域名上,那么您可以使用标准的xhr(ajax)请求,而不必担心跨域的问题。

Alternatively, your proxy server can wrap the data in a jsonp callback and you can use the method mentioned above. 或者,您的代理服务器可以将数据包装在jsonp回调中,您可以使用上面提到的方法。

If you are using jQuery, then xhr and jsonp requests are built-in methods and so make doing the coding very easy. 如果您使用的是jQuery,那么xhr和jsonp请求是内置方法,因此编写代码非常容易。 Other common js libraries should also support these. 其他常见的js库也应该支持这些。 If you are coding all of this from scratch, its a little more work but not terribly difficult. 如果你从头开始编写所有这些,那么它的工作要多一些,但并不是非常困难。

Now, once you get your data hopefully its just json. 现在,一旦你得到你的数据,希望它只是json。 Then there's no parsing needed. 然后就不需要解析了。

However, if you end up having to stick with an xml/rss version, and if you're jQuery, you can simply use jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ . 但是,如果你最终不得不坚持使用xml / rss版本,并且如果你是jQuery,你可以简单地使用jQuery.parseXML http://api.jquery.com/jQuery.parseXML/

better convert xml to json. 更好地将xml转换为json。 http://jsontoxml.utilities-online.info/ http://jsontoxml.utilities-online.info/

after converting if you need to print json object check this tutorial http://www.w3schools.com/json/json_eval.asp 转换后如果需要打印json对象请查看本教程http://www.w3schools.com/json/json_eval.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM