vvohra87
vvohra87

Reputation: 5664

Getting the InnerXML of an Element using REXML Document and Ruby

I have looked everywhere I think, but not found an answer.

I am consuming a SOAP API and I wish to store only part of the response in the database as XML.

The code is as follows:

require 'rexml/document'
doc = REXML::Document.new(response.to_xml)
data = doc.root.elements['//SearchResult'].to_s

This gives me all the XML inside the node of my response.

I want only the contents of that node, not the node.

Right now I get:

<SearchResult>
    <bla></bla>
    <bla2></bla2>
</SearchResult>

But I only want:

<bla></bla>
<bla2></bla2>

I'm using ruby 1.9.3-head with Rails 3.2.x.

I found a .value() method somewhere but that doesn't work on elements, which is what I get from the XPath search.

Please advise.

Upvotes: 2

Views: 1153

Answers (1)

undur_gongor
undur_gongor

Reputation: 15954

doc.root.elements['//SearchResult'].elements.each do | elem |
  p elem
end

gives

<bla> ... </>
<bla2> ... </>

So, with

data = doc.root.elements['//SearchResult'].elements.map(&:to_s)

you can retrieve an array of String representations of all sub-nodes.

Upvotes: 2

Related Questions