require 'rubygems'
require 'active_support/core_ext'
items = Hash.from_xml('<inventory><item><name>One</name></item><item><name>Two</name></item></inventory>')
print items.to_xml()
输出:
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<inventory>
<item type="array">
<item>
<name>One</name>
</item>
<item>
<name>Two</name>
</item>
</item>
</inventory>
</hash>
我想要的是(<item type="array">
标签被杀死):
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<inventory>
<item>
<name>One</name>
</item>
<item>
<name>Two</name>
</item>
</hash>
怎么做?
更新,添加skip_types
选项没有多大帮助:
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<inventory>
<item>
<item>
<name>One</name>
</item>
<item>
<name>Two</name>
</item>
</item>
</inventory>
</hash>
最佳答案
您可以使用 XmlSimple
gem 实现所需的行为:
gem install xml-simple
然后
require 'xmlsimple'
xml = '<inventory><item><name>One</name></item><item><name>Two</name></item></inventory>'
items = XmlSimple.xml_in(xml, KeepRoot: true)
#=> {"inventory"=>[{"item"=>[{"name"=>["One"]}, {"name"=>["Two"]}]}]}
puts XmlSimple.xml_out(items, KeepRoot: true)
# <inventory>
# <item>
# <name>One</name>
# </item>
# <item>
# <name>Two</name>
# </item>
# </inventory>
关于ruby-on-rails - 如何删除 ActiveSupport 的 from/to xml 中的数组标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23862541/