Ruby REXML: Get Value Of An XML Element

Jarred picture Jarred · Nov 18, 2011 · Viewed 8.5k times · Source

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"?

Answer

LarsH picture LarsH · Nov 18, 2011

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()") {...