2

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
4

2 に答える 2

2

ドキュメントを見ると、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"
于 2011-02-27T07:45:29.930 に答える
2

SuppressEmpty オプションをコマンドに追加することもできます。
XmlSimple.xml_out([{...}], 'SuppressEmpty' => nil)。

から - http://xml-simple.rubyforge.org/

于 2013-06-03T18:39:49.827 に答える