Search code examples
ruby-on-railsrubyxmlxpathrexml

Ruby REXML: Get Value Of An XML Element


I am trying to put the values of some xml elements into an array using rexml. Here is an example of what I am doing:

doc = Document.new("<data><title>This is one title</title><title>This is another title</title></data>")
XPath.each( doc, "*/title") { |element| 
    puts element.text
}

However, that outputs:

[<title> ... </>, <title> ... </>] 

How can I get it to output an array containing "This is one title" and "This is another title"?


Solution

  • Moving my comment to an answer, per request:

    While puts may convert its argument its argument to a string anyway, you can have the XPath return the text node in the first place:

    XPath.each(doc, "*/title/text()") {...