我正在使用 Last.fm API,我正在尝试获取有关某个用户的大量信息并以xml格式返回。所以,在我看来,这是呼吁:
<%= form_tag fetch_user_path, :remote => true, :'data-type' => 'xml', :id => 'search' do %>
<%= text_field_tag :q %>
<% end %>
所以,正如你所看到的,它期待XML,我使用jQuery正确地处理了回调。然后,在我的控制器中:
# fetch_controller.rb
def user
username = params[:q].gsub(' ','+')
get_info_url = "http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=#{username}&api_key=#{API_KEY}"
get_friends_url = "http://ws.audioscrobbler.com/2.0/?method=user.getfriends&user=#{username}&api_key=#{API_KEY}"
respond_to do |format|
format.xml {
begin
@info = Nokogiri::XML(open(get_info_url))
@friends = Nokogiri::XML(open(get_friends_url))
rescue Exception => e
if e.message == '400 Bad Request'
render xml: { :error => 'User not found.' }, :status => 400
else
render xml: { :error => 'Connection to Last.fm failed.' }, :status => 500
end
else
# Here, I want to render @info + @friends!
render xml: @info
end
}
end
这样,我正确地返回了 get_info_url
返回的 xml。但是,我想将该 xml 连接到 get_friends_url
返回的 xml 中。我该怎么做呢?
按照本·米勒的回答,我的回调出现了一个错误。我认为这与包含xml version
的两个xml文件有关。也许合并的文件没有?我看到xml文件正在连接,以下是它们使用console.log
的外观:
Error: Invalid XML: <?xml version="1.0"?>
<Combined>
<UserInfo>
<?xml version="1.0" encoding="utf-8"??>
<lfm status="ok">
<user>
# lots of info about the user
</user>
</lfm>
</UserInfo>
<FriendInfo>
<?xml version="1.0" encoding="utf-8"??>
<lfm status="ok">
<friends for="user" page="1" perpage="50" totalpages="2" total="96">
# lots of info about the user's friends
</friends>
</lfm>
</FriendInfo>
</Combined>
一个选项是将两个XML对象转换为字符串并连接它们,然后包装一个新的根节点。
或者你可以用Nokogiri构建器来做
def user
username = params[:q].gsub(' ','+')
get_info_url = "http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=#{username}&api_key=#{API_KEY}"
get_friends_url = "http://ws.audioscrobbler.com/2.0/?method=user.getfriends&user=#{username}&api_key=#{API_KEY}"
respond_to do |format|
format.xml {
begin
info_xml = Nokogiri::XML(open(get_info_url))
friends_xml = Nokogiri::XML(open(get_friends_url))
builder = Nokogiri::XML::Builder.new do |xml_out|
xml_out.Combined {
xml_out.UserInfo {
node = info_xml.at_xpath("//user")
xml_out << node.to_xml.to_str
}
xml_out.FriendInfo {
node = friends_xml.at_xpath("//friends")
xml_out << node.to_xml.to_str
}
}
end
rescue Exception => e
if e.message == '400 Bad Request'
render xml: { :error => 'User not found.' }, :status => 400
else
render xml: { :error => 'Connection to Last.fm failed.' }, :status => 500
end
else
render xml: builder.to_xml
end
}
end
end