tags:

views:

345

answers:

3

If I have a string which may contain any characters (including '/', '&',etc...) how do convert it safely into XML that can be stored like this:

<myelement>mystring</myelement>

Does it need to be CDATA, or can I easily convert it using a ruby function?

+3  A: 

The CGI module has an escapeHTML method.

CGI.escapeHTML("&<>")
#=> "&amp;&lt;&gt;"
sepp2k
+3  A: 
require 'rexml/document'
doc = REXML::Document.new
root = doc.add_element "Alpha"
root.add_text "now is & the < time > ' for \" me"
doc.write

Produces:

<Alpha>now is &amp; the &lt; time &gt; &apos; for &quot; me</Alpha>
DigitalRoss
A: 

There is a library in ruby called REXML for working with xml. It might be useful for what you need. Here's a link to a tutorial. http://www.germane-software.com/software/rexml/docs/tutorial.html

Narmada Sambaturu