Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REXML - How to extract a single element

Tags:

ruby

rexml

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

like image 444
Adrian Avatar asked Mar 10 '26 16:03

Adrian


1 Answers

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.

like image 92
undur_gongor Avatar answered Mar 12 '26 05:03

undur_gongor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!