Ruby and libxml: Collect your XML::Node::Set

Use collect and map in Ruby says Lucas Carlson. Thanks for pointing out that code arthritis, Lucas.

So, I was working with the libxml-ruby library (fast XML parsing) and found some loops in my code which could be converted. But, XML::Node::Set did not support collect. I mumbled something inaudible, grabbed the Pickaxe book, found the section on Enumerable, read for a bit, then just tried to mix it in:


# Mixes in Enumerable, to enable "collect" and friends
module XML
  class XML::Node::Set
    include Enumerable
  end
end

I put this at the top of my own library file, and suddenly I could do stuff like:


# photo is a XML::Node::set
photo.find('tags/tag').collect { |tag| tag.child.to_s }
# => ["funky", "rubylicious", "functional"]

This does an XPath expression, and walks through the result, collecting results, and then returns the whole chunk as an Array of tags as strings.

Thanks, Lucas, thanks libxml-ruby, thanks Matz.

*Update*: This mailing list post says that the above is going into 0.4, which seems to be coming along at a brisk pace. Some fantastic news in the shape of an upcoming patch that adds XmlTextReader API support. Good times.

Published by olleolleolle

Olle is a programmer, enjoying sunny Malmö in Sweden.

Join the Conversation

2 Comments

  1. I think you’re not getting Enumerable mixed in because of the install problems you posted about before – for the last release we added a ruby shim ‘libxml.rb’ that loaded the library, and defined some additional methods on the classes. These were mostly providing a more convenient interface, part of which was including Enumerable everywhere it made sense.

    Anyway, there’s been ongoing work to fix our gem install problems – It’d be great if you could elaborate on the install probs you had over on the mailing list:

    http://rubyforge.org/mail/?group_id=494

  2. Thanks for the link, now I’ve joined the devel list.

    I’m aware of the libxml.rb, that’s where I got the idea of including the Enumerable, and XML::Node::Set didn’t have that mixin included in it, so I just did that, first in the gem file, and then moved it to my own code.

    I see that this patch does some cleaning up in the XML::Node::Set, but nothing about Enumerable.

    I’ll see what I can do about the “build the gem better for Mac” issue. Perhaps some friend of mine haven’t built it already, and we can work together to gather some results.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.