logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma

xml_builder.ex (1242B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.XmlBuilder do
  5. def to_xml({tag, attributes, content}) do
  6. open_tag = make_open_tag(tag, attributes)
  7. content_xml = to_xml(content)
  8. "<#{open_tag}>#{content_xml}</#{tag}>"
  9. end
  10. def to_xml({tag, %{} = attributes}) do
  11. open_tag = make_open_tag(tag, attributes)
  12. "<#{open_tag} />"
  13. end
  14. def to_xml({tag, content}), do: to_xml({tag, %{}, content})
  15. def to_xml(content) when is_binary(content) do
  16. to_string(content)
  17. end
  18. def to_xml(content) when is_list(content) do
  19. for element <- content do
  20. to_xml(element)
  21. end
  22. |> Enum.join()
  23. end
  24. def to_xml(%NaiveDateTime{} = time) do
  25. NaiveDateTime.to_iso8601(time)
  26. end
  27. def to_doc(content), do: ~s(<?xml version="1.0" encoding="UTF-8"?>) <> to_xml(content)
  28. defp make_open_tag(tag, attributes) do
  29. attributes_string =
  30. for {attribute, value} <- attributes do
  31. value = String.replace(value, "\"", "&quot;")
  32. "#{attribute}=\"#{value}\""
  33. end
  34. |> Enum.join(" ")
  35. [tag, attributes_string] |> Enum.join(" ") |> String.trim()
  36. end
  37. end