Convert an arbitrary string to xml in ruby

Viewed 15884

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?

5 Answers

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