我有一个Rails控制器,它将以XML格式输出一个哈希 - 例如:
class MyController < ApplicationController
# GET /example.xml
def index
@output = {"a" => "b"}
respond_to do |format|
format.xml {render :xml => @output}
end
end
end
Run Code Online (Sandbox Code Playgroud)
但是,Rails添加了一个我不想要的<hash>标签,即:
<hash>
<a>
b
</a>
</hash>
Run Code Online (Sandbox Code Playgroud)
我怎样才能输出这个呢?
<a>
b
</a>
Run Code Online (Sandbox Code Playgroud)
the*_*RON 18
我想如果你要将一个对象转换为XML,你需要一个包装所有东西的标签,但你可以自定义包装器的标签名称:
def index
@output = {"a" => "b"}
respond_to do |format|
format.xml {render :xml => @output.to_xml(:root => 'output')}
end
end
Run Code Online (Sandbox Code Playgroud)
这将导致:
<output>
<a>
b
</a>
</output>
Run Code Online (Sandbox Code Playgroud)
我有同样的问题;
这是我的XML:
<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<Contact type="array">
</Contact>
</Contacts>
Run Code Online (Sandbox Code Playgroud)
我在用这个:
entries.to_xml
Run Code Online (Sandbox Code Playgroud)
将哈希数据转换为XML,但这会将条目的数据包装进去 <hash></hash>
所以我修改了:
entries.to_xml(root: "Contacts")
Run Code Online (Sandbox Code Playgroud)
但仍然将转换后的XML包装在"联系人"中.将我的XML代码修改为
<Contacts>
<Contacts>
<Contact type="array">
<Contact>
<Name></Name>
<Email></Email>
<Phone></Phone>
</Contact>
</Contact>
</Contacts>
</Contacts>
Run Code Online (Sandbox Code Playgroud)
所以它增加了额外的ROOT,我不会在那里.
现在解决这个问题的方法是:
entries["Contacts"].to_xml(root: "Contacts")
Run Code Online (Sandbox Code Playgroud)
避免<hash></hash>或包含任何其他根.干杯!!
| 归档时间: |
|
| 查看次数: |
5281 次 |
| 最近记录: |