Convert an arbitrary string to xml in ruby

The CGI module has an escapeHTML method.

CGI.escapeHTML("&<>")
#=> "&amp;&lt;&gt;"

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>

In Ruby 1.9.2 to escape XML special characters in Strings, use the 'encode' method.

Example, if you have:

my_string = 'this is "my" complicated <String>'

For XML attributes use:

"<node attr=#{my_string.encode(:xml => :attr)} />"

Generates:

<node attr="this is &quot;my&quot; complicated &lt;String&gt;" />

For XML text use:

"<node>#{my_string.encode(:xml => :text)}</node>"

Generates:

<node>this is "my" complicated &lt;String&gt;</node>

Tags:

Xml

String

Ruby