rubyrexml

How do I grab a really simple element using XML?


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?


Solution

  • 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.