3

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

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
Adrian
  • 143
  • 1
  • 4
  • 13

1 Answers1

3

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.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
  • Thanks for the advice. For this particular test there will only be one name (It's getting metadata of a file). I have other tests where more than one elements will be returned but I think I know what to do now. Thanks again. – Adrian Sep 08 '11 at 11:48