开发者

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

开发者 https://www.devze.com 2023-04-03 09:57 出处:网络
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.

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 th开发者_Go百科at 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


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 ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号