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?
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 "my" complicated <String>" />
For XML text use:
"<node>#{my_string.encode(:xml => :text)}</node>"
Generates:
<node>this is "my" complicated <String></node>
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 & the < time > ' for " me</Alpha>
The CGI module has an escapeHTML method.
CGI.escapeHTML("&<>")
#=> "&<>"
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 <String>�"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With