开发者

In Ruby, is there a way to use XmlSimple when some values are nil?

开发者 https://www.devze.com 2023-02-13 17:54 出处:网络
As the nil will choke XmlSimple: >> require \'xmlsimple\' => true >> XmlSimple.xml_out([{\'a\' => 1}, {\'a\' => 3}])

As the nil will choke XmlSimple:

>> require 'xmlsimple'
=> true

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

but if it is the following, then it will give an error:

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


If you take a look at the documentation it mentions that when using xml_out you should avoid nil values. I would recommend one of the following approaches:

# 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"


You can also just add the SuppressEmpty option to the command.
XmlSimple.xml_out([{...}], 'SuppressEmpty' => nil).

from - http://xml-simple.rubyforge.org/

0

精彩评论

暂无评论...
验证码 换一张
取 消