Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Okay, so I've resolved this problem for myself just now. The solution is in two parts:</p> <p>First, the content type you are matching is incorrect. If you run this line, after you do your get, it will tell you what the content type is for the document you are getting:</p> <pre><code>page.response['content-type'] # =&gt; 'application/xml', not 'text/xml' </code></pre> <p>When I use mechanize to get your page ('http://dl.dropbox.com/u/344349/xml.xml'), I see 'application/xml' as the content type.</p> <p>Second, you're not using PluggableParser correctly. Using XMLParser as you have it here will generate <code>NoMethodError: undefined method 'parse' for nil:NilClass</code>. Change the class definition to use Nokogiri::XML instead:</p> <pre><code>class XmlParser &lt; Mechanize::File attr_reader :xml def initialize(uri = nil, response = nil, body = nil, code = nil) @xml = Nokogiri::XML(body) super uri, response, body, code end end </code></pre> <p>Then, set this as the parser for the correct content type:</p> <pre><code>mech.pluggable_parser['application/xml'] = XmlParser </code></pre> <p>To use this, you'll get your page the same as before, and then reference the xml attribute of the page object as a <a href="http://nokogiri.org/Nokogiri/XML/Document.html" rel="nofollow">Nokogiri::XML::Document</a> instance, which is a subclass of <a href="http://nokogiri.org/Nokogiri/XML/Node.html" rel="nofollow">Nokogiri::XML::Node</a>. Fortunately, <a href="http://mechanize.rubyforge.org/Mechanize/Page.html#method-i-search" rel="nofollow">Mechanize::Page.search</a> is just a wrapper around <a href="http://mechanize.rubyforge.org/Mechanize/Page.html#method-i-search" rel="nofollow">Nokogiri::XML::Node.search</a>, so you can search the same way you expect, pretty much. Like this:</p> <pre><code>page.xml.search 'catalog' </code></pre> <p>A further refinement would be to map XmlParser.search to the Nokogiri .search methods:</p> <pre><code># This is the same as what Mechanize::Page does class XmlParser &lt; Mechanize::File extend Forwardable def_delegators :@xml, :search, :/, :at end </code></pre> <p>This lets you perform your searches directly on the page instance:</p> <pre><code>page.search 'catalog' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload