Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby convert single quotes to double quotes in XML

Despite the fact that XML attributs can be defined using single or double quotes, my user is trying to integrate my software with another one that will not accept single quoted attribut values.

I user REXML to generate my XMLs.

Is there a way to REXML generate double quoted attribute values? If not, is there a way for me to convert it easily?

Thanks

like image 698
Ricardo Acras Avatar asked Oct 13 '10 19:10

Ricardo Acras


People also ask

How do you use double quotes in XML?

From the XML specification: To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "'", and the double-quote character (") as """.

Does XML Use single or double quotes?

XML Attributes Must be Quoted Attribute values must always be quoted. Either single or double quotes can be used.

How do you print double quotes in Ruby?

Alternate double quotesThe %Q operator (notice the case of Q in %Q ) allows you to create a string literal using double-quoting rules, but without using the double quote as a delimiter. It works much the same as the %q operator. Just like double quotes, you can interpolate Ruby code inside of these string literals.

How do you add a double quote to a string in Ruby?

Single-quoted and double-quoted strings are (almost) equivalent in Ruby. Of course, you have to escape \' inside single-quoted strings and \" inside double-quoted strings.


2 Answers

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.new
doc.context[:attribute_quote] = :quote  # <-- Set double-quote as the attribute value delimiter

root = doc.add_element('root')
root.add_attribute('val', '123')

doc.write(STDOUT)

Running that yields:

$ ruby test.rb
<root val="123"/>
$
like image 193
Rômulo Ceccon Avatar answered Oct 17 '22 05:10

Rômulo Ceccon


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(/"/, '&quot;')}"]
    end
  ^ )
like image 30
AboutRuby Avatar answered Oct 17 '22 05:10

AboutRuby