Recently, I was integrating with some web services and needed to parse some XML. REXML's XPath is a great tool for this. XPath has a method #each that will allow you to iterate over all the elements that match the XPath. So, to collect all the text nodes for an XPath, you could do something like this:
items = []
REXML::XPath.each(@document.root, "//list/items").each do |element|
items << element.text
end
XPath implements the each method, but isn't an Enumerable so it doesn't support methods like collect. Using Enumerable::Enumerator and Rails' to_proc makes this code simpler:
Enumerable::Enumerator.new(REXML::XPath, :each, @document.root, "//list/items").collect(&:text)
3 comments:
Would the following not work for you?
items = []
@document.root.each_element("//list/items") do |element|
items << element.text
end
Or indeed, since this uses the Elements class, which is enumerable:
@document.root.elements.collect("//list/items") { |e| e.text }
Yes, that would work, too. I forgot about Elements being Enumerable.
Post a Comment