您如何知道何时使用XML解析器以及何时使用ActiveResource? [英] How do you know when to use an XML parser and when to use ActiveResource?

查看:88
本文介绍了您如何知道何时使用XML解析器以及何时使用ActiveResource?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用ActiveResource解析更像HTML文档的Web服务,但不断出现404错误.

I tried using ActiveResource to parse a web service that was more like a HTML document and I kept getting a 404 error.

我需要为此任务使用XML解析器而不是ActiveResource吗?

Do I need to use an XML parser for this task instead of ActiveResource?

我的猜测是,ActiveResource仅在您使用另一个Rails应用程序中的数据并且XML数据可轻松转换为Rails模型时才有用.例如,如果Web服务是范围更广的XML(例如HTML文档或RSS feed),则您想使用诸如hpricot或nokogiri之类的解析器.这是正确的吗?

My guess is that ActiveResource is only useful if you are consuming data from another Rails app and the XML data is easily translatable to a Rails model. For example, if the web service is more wide-ranging XML like a HTML document or an RSS feed, you want to use a parser like hpricot or nokogiri. Is this correct?

您如何知道何时使用XML解析器以及何时使用ActiveResource?

How do you know when to use an XML parser and when to use ActiveResource?

推荐答案

更新:ActiveResource也不是XML解析器.它是REST使用者,允许您与远程资源进行交互,类似于ActiveRecord模型.它确实在后台使用了XML解析器(我通过下面显示的ActiveSupport的XmlMini进行假设).

Update: ActiveResource is also not an XML parser. It is a REST consumer allowing you to interact with a remote resource similar to how you would an ActiveRecord model. It does use an XML parser under the hood (I'm assuming through ActiveSupport's XmlMini I show below).

ActiveResource对XML内容的结构有一些严格的要求,并且在与另一个Rails应用程序的REST API进行交互时效果最佳.它不打算对HTML页面进行常规的屏幕抓取.为此,请直接使用Nokogiri.

ActiveResource has some strict requirements about the structure of the XML content and works best when interacting with the REST API of another Rails application. It is not intended to do generic screen scraping of an HTML page. For that use Nokogiri directly.

ActiveSupport不是XML解析器,它是有用的Ruby方法和类的各种集合.但是,它确实为许多不同的XML解析器提供了包装,从而为您提供了一致的接口.

ActiveSupport isn't an XML parser, it is a miscellaneous collection of useful Ruby methods and classes. However, it does offer a wrapper around many different XML parsers giving you a consistent interface.

您可以查看正在使用哪个XML解析器,并切换到其他XML解析器.在script/console中尝试.

You can see which XML parser is being used and switch to a different XML parser. Try this in script/console.

ActiveSupport::XmlMini.backend # => ActiveSupport::XmlMini_REXML
ActiveSupport::XmlMini.backend = 'Nokogiri'
ActiveSupport::XmlMini.backend # => ActiveSupport::XmlMini_Nokogiri
# it will now use Nokogiri

但是,它仍将使用Nokogiri中的XML解析器,该解析器采用严格有效的标记.大多数HTML页面都不符合此严格要求,因此最好直接使用Nokogiri的HTML解析器,而不要通过ActiveSupport.

However, that will still use the XML parser in Nokogiri which assumes strict, valid markup. Most HTML pages do not fit this strict requirement and therefore it is better to use Nokogiri's HTML parser directly instead of going through ActiveSupport.

doc = Nokogiri::HTML(...)

这篇关于您如何知道何时使用XML解析器以及何时使用ActiveResource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆