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 ;-) Commented Sep 18, 2009 at 11:21

5 Answers 5

55

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>
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Unfortunately, it does not escape all the XML-invalid symbols. For example, \v
5

The CGI module has an escapeHTML method.

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

2 Comments

I think it's better to specifically use XML escape rather than HTML escape methods.
It doesn't escape ASCII control characters.
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;�"

Comments

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 Comment

would be better if more detail provided to solve the question.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.