cmaughan
cmaughan

Reputation: 2634

Convert an arbitrary string to xml in ruby

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?

Upvotes: 25

Views: 17112

Answers (5)

Ngoral
Ngoral

Reputation: 4824

This answer is mostly for Rails, but, however, might be useful. I looked up how rails .to_xml works and found out you can use Builder::XChar#encode from builder gem.

Builder::XChar.encode(%(this is "my" complicated <String>\v))
#=> "this is \"my\" complicated &lt;String&gt;�"

Upvotes: 4

salidux
salidux

Reputation: 626

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>

Upvotes: 55

Narmada Sambaturu
Narmada Sambaturu

Reputation: 9

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

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146141

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>

Upvotes: 6

sepp2k
sepp2k

Reputation: 370387

The CGI module has an escapeHTML method.

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

Upvotes: 5

Related Questions