gpt4 book ai didi

ruby-on-rails - 如何杀死这个来自/到 ActiveSupport 的 xml 中的数组标记?

转载 作者:太空宇宙 更新时间:2023-11-03 16:01:33 26 4
gpt4 key购买 nike

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 的 xml 中的数组标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23862541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com