REXML - How to extract a single element

怎甘沉沦 提交于 2019-12-10 10:03:18

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/7347218/rexml-how-to-extract-a-single-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!