Skip to content

Instantly share code, notes, and snippets.

@Abica
Last active March 18, 2019 03:08
Show Gist options
  • Save Abica/88c728c053e4743849ad1018ac2b0941 to your computer and use it in GitHub Desktop.
Save Abica/88c728c053e4743849ad1018ac2b0941 to your computer and use it in GitHub Desktop.
Example serializing an arbitrary elixir structure as xml and returning it from a phoenix endpoint
defmodule WhateverWeb.AController do
use WhateverWeb, :controller
# get "/whatever/:format", WhateverWeb.AController, :some_action
def some_action(conn, %{"format" => "xml"} = _params) do
example_data = %{
name: "Buy Guy",
title: "buyer",
items: [
%{name: "A", cost: 10, qty: 1},
%{name: "B", cost: 10, qty: 2}
]
}
xml =
%{root_container: example_data}
|> to_xml
|> XmlBuilder.generate
conn
|> put_resp_content_type("text/xml")
|> send_resp(200, xml)
end
def some_action(conn, _params) do
conn
|> send_resp(404, "Not found")
end
defp to_xml(data) when is_list(data) or is_map(data) do
data
|> Enum.map(&to_xml/1)
end
defp to_xml({k, v}) do
{k, %{}, to_xml(v)}
end
defp to_xml(v), do: v
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment