Ruby convert single quotes to double quotes in XML

做~自己de王妃 提交于 2019-11-30 23:19:12

问题


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


回答1:


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"/>
$



回答2:


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
  ^ )


来源:https://stackoverflow.com/questions/3927507/ruby-convert-single-quotes-to-double-quotes-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!