25

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?

1
  • Sorry Jonas, I put the xml in the text and it got removed; lesson learned; had to place it in a code block ;-)
    – cmaughan
    Commented Sep 18, 2009 at 11:21

5 Answers 5

54

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>
6
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>
1
  • Unfortunately, it does not escape all the XML-invalid symbols. For example, \v
    – Ngoral
    Commented Jan 16, 2019 at 10:20
5

The CGI module has an escapeHTML method.

CGI.escapeHTML("&<>")
#=> "&amp;&lt;&gt;"
2
  • 1
    I think it's better to specifically use XML escape rather than HTML escape methods.
    – fatuhoku
    Commented Sep 2, 2016 at 13:31
  • It doesn't escape ASCII control characters.
    – khiav reoy
    Commented Aug 24, 2020 at 7:24
4

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;�"
0

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

1
  • would be better if more detail provided to solve the question. Commented Jun 4, 2015 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.