Ruby将单引号转换为XML中的双引号

时间:2022-09-15 16:09:52

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.

尽管可以使用单引号或双引号定义XML属性,但我的用户正在尝试将我的软件与另一个不接受单引号属性值的软件集成。

I user REXML to generate my XMLs.

我用户REXML来生成我的XML。

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

有没有办法让REXML生成双引号属性值?如果没有,有没有办法让我轻松转换它?

Thanks

谢谢

2 个解决方案

#1


19  

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:

截至2007年2月,有一种支持的方法来确定引用字符。这些更改在2007年7月合并到Ruby源代码中,并且应该可以在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


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.

我已经看到这个代码来做这个。但它来自2003年的邮件列表帖子,它也承诺采用更优雅(和支持)的方式。可能不是最好的,但它可以工作,尝试一下。

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

#1


19  

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:

截至2007年2月,有一种支持的方法来确定引用字符。这些更改在2007年7月合并到Ruby源代码中,并且应该可以在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


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.

我已经看到这个代码来做这个。但它来自2003年的邮件列表帖子,它也承诺采用更优雅(和支持)的方式。可能不是最好的,但它可以工作,尝试一下。

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