Merge develop
[akkoma] / lib / xml_builder.ex
1 defmodule Pleroma.XmlBuilder do
2 def to_xml({tag, attributes, content}) do
3 open_tag = make_open_tag(tag, attributes)
4
5 content_xml = to_xml(content)
6
7 "<#{open_tag}>#{content_xml}</#{tag}>"
8 end
9
10 def to_xml({tag, %{} = attributes}) do
11 open_tag = make_open_tag(tag, attributes)
12
13 "<#{open_tag} />"
14 end
15
16 def to_xml({tag, content}), do: to_xml({tag, %{}, content})
17
18 def to_xml(content) when is_binary(content) do
19 to_string(content)
20 end
21
22 def to_xml(content) when is_list(content) do
23 for element <- content do
24 to_xml(element)
25 end
26 |> Enum.join()
27 end
28
29 def to_xml(%NaiveDateTime{} = time) do
30 NaiveDateTime.to_iso8601(time)
31 end
32
33 def to_doc(content), do: ~s(<?xml version="1.0" encoding="UTF-8"?>) <> to_xml(content)
34
35 defp make_open_tag(tag, attributes) do
36 attributes_string =
37 for {attribute, value} <- attributes do
38 value = String.replace(value, "\"", "&quot;")
39 "#{attribute}=\"#{value}\""
40 end
41 |> Enum.join(" ")
42
43 [tag, attributes_string] |> Enum.join(" ") |> String.trim()
44 end
45 end