Search code examples
rubyrexml

REXML - Having trouble asserting a value is present in XML response


I got help here this morning using REXML and the answer helped me understand more about it. However I've encountered another problem and can't seem to figure it out.

My response is like this:

<?xml version="1.0"?>
<file>
<link a:size="2056833" a:mimeType="video/x-flv" a:bitrate="1150000.0" a:height="240" a:width="320" rel="content.alternate"> https://link.com</link>
</file>

So, what I want to do is assert that a:mimeType is video/x-flv

Here's what I have tried:

xmlDoc = REXML::Document.new(xml)
assert_equal xmlDoc.elements().to_a("file/link['@a:mimeType']").first.text, 'video/x-flv'

and also:

assert xmlDoc.elements().to_a("file/link['@a:mimeType']").include? 'video/x-flv'

and various combinations. I actually get lots of these links back but I only really care if one of them has this mimeType. Also, some of the links don't have mimeType.

Any help greatly appreciated.

Thanks, Adrian


Solution

  • text is retrieving for text content of elements (text between tags). You want to access an "attribute". Try

    xmlDoc.elements().to_a("file/link").first.attributes['a:mimeType']
    

    To see if either of the links has the correct mimeType, you can convert the array of elements into an array of mimeType attributes and check if it contains the right value:

    xmlDoc.elements().to_a("file/link").map { | elem | elem.attributes['a:mimeType'] }.include? 'video/x-flv'
    

    UPDATE

    Or much simpler, check if there is an element with the attribute mimeTypes having the right value:

    xmlDoc.elements().to_a("file/link[@a:mimeType='video/x-flv']") != []
    

    Thanks for teaching me something about XPath ;-)