Rexml: replace several text nodes by a single one

Hi,

this sounds simple but I just don’t get it…

I want to replace the text child nodes of an REXML::Element by a new,
single text node…

In order to do that, I want to remove any previous text nodes first


require ‘rexml/document’
include REXML

doc = Document.new(" ")
a = doc.elements[‘a’]
a.delete_element(‘b’)

assert: a.texts.size == 2

try #1

a.texts.clear

–> can’t modify frozen array (TypeError)

try #2

iterate all elements, call delete_element: fails, because

a.elements.size == 0

MAGIC CODE GOES HERE!!!

a.text = “I am the only text in this element”

assert a.texts.size == 1


I don’t think that setting all text nodes to zero-length string values
is a good solution.

thanks for your help!

regards
peter

I got something to work at least. This should give you an idea of how I
did it:

def remove!
  case @node.node_type
  when :text
    @node.value = ''
  else
    @node.parent.send("delete_#{@node.node_type}", @node )
  end
end

def empty!
  each { |n| n.remove! }
end

T.

Pete wrote:

Hi,

this sounds simple but I just don’t get it…

I want to replace the text child nodes of an REXML::Element by a new,
single text node…

In order to do that, I want to remove any previous text nodes first

OMG, I was just about to ask the same thing. I was trying to delete
them all first, but I don;t even get how to do that:

node.parent.delete( node ) # soden;t seem to to work

Do I really have to do

case node
when REXML::Element
node.parent.delete_element( node )
when REXML::Attribute
node.parent.delete_element( node )
when REXML::Text
node.parent.delete_text( node )
else
# else ?
end

Tell me it ain’t so!

T.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs