0

My code:

require 'rexml/document'
require 'xpath'

doc = REXML::Document.new(xml)
XPath.each(doc, "*/categoryName") { |element| puts element.text }

I am trying to take object xml where xml is a string of xml... and retrieve some text ie - I want this text

I thought the code above would work, but it is giving me the following error:

undefined method `each' for XPath:Module
DaveyGravy
  • 21
  • 5
  • Using [Nokogiri](http://nokogiri.org) instead: `doc = Nokogiri.XML(xml); puts doc.xpath('*/categoryName').map(&:text)` – Phrogz Jun 26 '13 at 19:31

2 Answers2

1

I'm not sure what 'xpath' library you're loading, but you don't want or need it. Confusing the matter is that REXML's documentation assumes that you have 'polluted' your global object via include REXML. Since you are not doing that, you need to provide the full path to the module:

require 'rexml/document'
doc = REXML::Document.new(xml)
REXML::XPath.each( doc, "*/category"){ |el| puts el.text }
Phrogz
  • 296,393
  • 112
  • 651
  • 745
0

I think you missed require rexml/xpath and try REXML::XPath.each. It will work.

require 'rexml/document'
require 'rexml/xpath'
doc = REXML::Document.new(xml)
REXML::XPath.each( doc, "*/category") { |element| puts element.text }

One example:

require 'rexml/document'
require 'rexml/xpath'

doc = REXML::Document.new("<p>some text <b>this is bold!</b> more text</p>")
REXML::XPath.each(doc, "*//b") { |element| puts element.text }
# >> this is bold!
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317