在Ruby中,当某些值为nil时,有没有办法使用XmlSimple?

时间:2011-02-25 22:51:03

标签: ruby xml-simple

因为nil会阻塞XmlSimple:

>> require 'xmlsimple'
=> true

>> XmlSimple.xml_out([{'a' => 1}, {'a' => 3}])
=> "<opt>\n  <anon a=\"1\" />\n  <anon a=\"3\" />\n</opt>\n"

但如果是以下内容,则会出错:

>> XmlSimple.xml_out([{'a' => 1}, {'a' => nil}])
ArgumentError: Use of uninitialized value!
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:798:in `value_to_xml'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `each'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `value_to_xml'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:848:in `value_to_xml'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:842:in `each'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:842:in `value_to_xml'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:807:in `value_to_xml'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `each'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `value_to_xml'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:239:in `xml_out'
    from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:259:in `xml_out'
    from (irb):4

2 个答案:

答案 0 :(得分:2)

如果你看一下documentation,它会提到当使用xml_out时你应该避免使用nil值。我建议采用以下方法之一:

# To create an empty anon element:
XmlSimple.xml_out([{'a' => 1}, {}])
=> "<opt>\n  <anon a=\"1\" />\n  <anon></anon>\n</opt>\n"

# To create an anon element with a blank 'a' attribute:
XmlSimple.xml_out([{'a' => 1}, {'a' => ''}])
=> "<opt>\n  <anon a=\"1\" />\n  <anon a=\"\" />\n</opt>\n"

# To remove the attribute entirely (with value of 3),
# but still create an empty anon tag:
XmlSimple.xml_out([{'a' => 1}, {'-a' => 3}])
=> "<opt>\n  <anon a=\"1\" />\n  <anon />\n</opt>\n"

# To remove the attribute entirely (with value of nil),
# but still create an empty anon tag:
XmlSimple.xml_out([{'a' => 1}, {'-a' => nil}])
=> "<opt>\n  <anon a=\"1\" />\n  <anon />\n</opt>\n"

答案 1 :(得分:2)

您也可以将SuppressEmpty选项添加到命令中。
XmlSimple.xml_out([{...}],'SuppressEmpty'=&gt; nil)。

来自 - http://xml-simple.rubyforge.org/