REXML: storing xml entity

  • Thread starter Yohanes Santoso
  • Start date
Y

Yohanes Santoso

Hi all,

I was wondering how to store free-form data (from user) with REXML.

##################################################
require 'rexml/document'

class REXML::Element
alias :eek:rig_initialize :initialize
def initialize( arg = UNDEFINED, parent=nil, context=nil )
orig_initialize(arg, parent, context)
yield self if block_given?
end
end

include REXML
output = ""
doc = Document.new
doc.add(Element.new("test_output"){|root|
root.add(Element.new("lt_literal"){|elt| elt.text = "<"})
root.add(Element.new("lt_entity"){|elt| elt.text = "&lt;")})
root.add(Element.new("amp_literal"){|elt| elt.text = "&"})})
doc.write(output, 2)
puts "Output: #{output}"

puts "--------------------------------------------------"
doc = Document.new(output)
doc.elements.each("test_output/*"){|elt| puts "text of #{elt.name}: #{elt.text}"}
##################################################

dede:~$ ruby tmp/try.rb
Output:
<test_output>
<lt_literal>&lt;</lt_literal>
<lt_entity>&lt;</lt_entity>
<amp_literal>&amp;</amp_literal>
</test_output>
--------------------------------------------------
text of lt_literal: <
text of lt_entity: <
text of amp_literal: &



Notice that the text of lt_entity is different than what I inputted
(it should be "&lt;").

For this case, I could have encapsulate done: elt.text =
CData.new("&lt;"), however, in general, do I have to scan the user
input for cases like this (XML entities)? But that would mean my
program now also has to know about XML-specific knowledge, which I
think is what REXML should shield me from.

My main question is this: for any string, how do I store it using
REXML so that when read back, I get the same exact content?

Thanks,
YS.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,061
Latest member
KetonaraKeto

Latest Threads

Top