rexml: replace several text nodes by a single one

P

Pete

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> <b/> </a>")
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
 
T

transfire

Pete said:
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.
 
T

transfire

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top