Search code examples
rubyrexml

REXML - How to extract a single element


I am writing some acceptance tests in ruby which involve asserting the presence of values in response XML.

My XML is like this:

<?xml version="1.0"?>
<file xmlns:dvi=xxxxx>
    <name>whatever</name>
</file>

There are other attributes but what is above should illustrate my point. Here is my ruby code:

xml = <the xml above>
xmlDoc = REXML::Document.new(xml)
puts xmlDoc.elements().to_a('file/name')

This prints out <name>whatever</name> but I want it to simply print out whatever

In this XML there will only ever be one name element. I have been able to print out just the text I want using elements.each but it seems like overkill.

Thanks, Adrian


Solution

  • Try

    xmlDoc.elements().to_a('file/name').first.text
    

    and then add some error treatment (this is not robust).

    The to_a returns an array of REXML elements. With first you retrieve the first (and supposedly the only) element. With text you access that elements text content.