Write your code as below :
require 'nokogiri'
@doc = Nokogiri::XML <<-EOXML
<?xml version="1.0"?>
<root>
<product>
<name>cool_fish</name>
<product_details>
<location>ocean</location>
<costs>
<msrp>9.99</msrp>
<margin>5.00</margin>
</costs>
</product_details>
</product>
<product>
<name>veggies</name>
<product_details>
<location>field</location>
<costs>
<msrp>2.99</msrp>
<margin>1.00</margin>
</costs>
</product_details>
</product>
</root>
EOXML
@doc.xpath("//product").each do |x|
puts x.at_xpath(".//location").text if x.at_xpath(".//name").text =~ /cool_fish/
end
# >> ocean
You are parsing an xml
, you should use Nokogiri::XML
. Your xpath
expression was also incorrect. You wrote #xpath
method, but you were using expression, which you should use with methods like css
or search
. I used at_xpath
method, as you were interested with the single node match inside the #each
block.
But you can use at
in place of #at_xpath
and search
in place of xpath
.
Remember search
and at
both understand CSS, as well as xpath expressions. search
or xpath
or css
all methods will give you NodeSet
, where as at
, at_css
or at_xpath
would give you a Node
. Once a Nokogiri
node will be in your hand, use text
method to get the content of that node.