Javascript 使用 Java Script 从 URL 解析 XML / RSS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8237923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing XML / RSS from URL using Java Script
提问by Arun Kumar Munusamy
Hi i want to parse xml/rss from a live url like http://rss.news.yahoo.com/rss/entertainmentusing pure Java Script(not jquery). I have googled a lot. Nothing worked for me. can any one help with a working piece of code.
嗨,我想 使用纯 Java 脚本(不是 jquery)从像http://rss.news.yahoo.com/rss/entertainment这样的实时 url 解析 xml/rss 。我已经谷歌了很多。没有什么对我有用。任何人都可以帮助处理一段工作代码。
回答by PointedEars
(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:
(您不可能在 google 上搜索很多。)一旦您解决了同源策略,并且如果资源使用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 2specification [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+ Coreor DOM Level 3 XPathmethods, e.g.
本质上:不需要解析。如果您想访问 XML 数据,请使用标准的DOM Level 2+ Core或DOM 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.jsfor 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. See pradeek's answerfor a solution that works in IE/MSXML. The following should work everywhere else:
但是,如果由于某种(错误的)原因,MIME 类型不是 XML MIME 类型,或者如果 DOM 实现无法识别它,您可以使用内置在最近浏览器中的解析器之一来解析responseText
属性值。有关适用于 IE/MSXML 的解决方案,请参阅pradeek 的答案。以下应该适用于其他任何地方:
var parser = new DOMParser();
var doc = parser.parseFromString(x.responseText, "text/xml");
Proceed as described above.
如上所述进行。
Use feature testsat 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).
回答by Geuis
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提要的大问题。
The common way to deal with loading data in javascript cross domain is calls JSONP. Basically, this means that the data you are retrieving is wrapped in a javascript callback function. You load the url with a script tag, and you define the function in your code. So when the script loads, it executes the function and passes the data to it as an argument.
处理javascript跨域加载数据的常用方法是调用JSONP。基本上,这意味着您正在检索的数据包含在 javascript 回调函数中。您使用脚本标记加载 url,并在代码中定义函数。因此,当脚本加载时,它会执行该函数并将数据作为参数传递给它。
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. That will make this a lot easier.
在继续之前,请检查您的数据源是否提供 json 格式和 JSONP 功能。这将使这更容易。
Now, if your data source doesn'tprovide 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. 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.
处理此问题的相对简单的方法是使用代理服务器。您的代理在您控制的某个地方运行,并充当中间人来获取您的数据。服务器加载您的 xml,然后您的 javascript 改为向它发送请求。如果代理服务器在同一个域名上运行,那么您可以只使用标准的 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. Other common js libraries should also support these. If you are coding all of this from scratch, its a little more work but not terribly difficult.
如果您使用的是 jQuery,那么 xhr 和 jsonp 请求是内置方法,因此可以非常轻松地进行编码。其他常见的js库也应该支持这些。如果您从头开始编写所有这些代码,则需要更多的工作,但并不是非常困难。
Now, once you get your data hopefully its just json. Then there's no parsing needed.
现在,一旦你得到你的数据,希望它只是 json。那么就不需要解析了。
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/。
回答by Nathan Sri
better convert xml to json. http://jsontoxml.utilities-online.info/
更好地将 xml 转换为 json。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