Ruby convert single quotes to double quotes in XML Ruby convert single quotes to double quotes in XML xml xml

Ruby convert single quotes to double quotes in XML


As of Feb 2007 there's a supported way of determining the quoting character. The changes were merged into Ruby sources on Jul 2007 and should be available on all versions since 1.8.6-p110:

require 'rexml/document'doc = REXML::Document.newdoc.context[:attribute_quote] = :quote  # <-- Set double-quote as the attribute value delimiterroot = doc.add_element('root')root.add_attribute('val', '123')doc.write(STDOUT)

Running that yields:

$ ruby test.rb<root val="123"/>$


I've seen this code around to do this. But it's from a 2003 mailing list post that also promises a more elegant (and supported) way of doing it. Might not be the best, but it could work, give it a try.

REXML::Attribute.class_eval( %q^    def to_string      %Q[#@expanded_name="#{to_s().gsub(/"/, '"')}"]    end  ^ )