0

I'm struggling to figure out XPath and REXML, every single thing I try, even copied from books, returns nil. And I'm trying to do the simplest possible output of data... my file looks like

<profile>
    <userid>3002</userid>
</profile>

I want to get 3002 out. What on Earth do I do?

GreenTriangle
  • 2,382
  • 2
  • 21
  • 35

2 Answers2

0

It would be better if you post a code. Well, just to show you a direction, try this:

require 'rexml/document'

xml = '<profile>
         <userid>3002</userid>
       </profile>'

doc = REXML::Document.new xml
item = REXML::XPath.first(doc, '//profile/userid').text
p item
#=> 3002

It finds first userid element inside profile and takes it's text.

Yevgeniy Anfilofyev
  • 4,827
  • 25
  • 27
0

You can use excellent Nokogiri Gem too. Here is how I'd code this -

require 'nokogiri'

xml = '<profile>
         <userid>3002</userid>
      </profile>'

doc = Nokogiri::XML.parse xml
p doc.at('userid').text
# => "3002"
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317