Saxy.Builder protocol (Saxy v1.5.0) View Source

Protocol for building XML content.

Deriving

This helps to generate XML content simple form in trivial cases.

There are a few required options:

  • name - tag name of generated XML element.
  • attributes - struct keys to be encoded as attributes.
  • children - a list of entries to be collected as element content. Each entry could be either:
    • key - value will be used as the content.
    • two-element tuple of key and transformer - struct value will be passed to the transformer. Transformer function could be a captured public function or a tuple of module and function.

Examples

defmodule Person do
  @derive {
    Saxy.Builder,
    name: "person", attributes: [:gender], children: [:name, emails: &__MODULE__.build_emails/1]
  }

  import Saxy.XML

  defstruct [:name, :gender, emails: []]

  def build_emails(emails) do
    count = Enum.count(emails)

    element(
      "emails",
      [count: Enum.count(emails)],
      Enum.map(emails, &element("email", [], &1))
    )
  end
end

iex> person = %Person{name: "Alice", gender: "female", emails: ["alice@foo.com", "alice@bar.com"]}
iex> Saxy.Builder.build(person)
{"person", [{"gender", "female"}], ["Alice", {"emails", [{"count", "2"}], [{"email", [], ["alice@foo.com"]}, {"email", [], ["alice@bar.com"]}]}]}

Custom implementation could be done by implementing protocol:

defmodule User do
  defstruct [:username, :name]
end

defimpl Saxy.Builder, for: User do
  import Saxy.XML

  def build(user) do
    element(
      "Person",
      [{"userName", user.username}],
      [element("Name", [], user.name)]
    )
  end
end

iex> user = %User{name: "Alice", username: "alice99"}
iex> Saxy.Builder.build(user)
{"Person", [{"userName", "alice99"}], [{"Name", [], ["Alice"]}]}

Link to this section Summary

Functions

Builds content to XML content in simple form.

Link to this section Types

Link to this section Functions

Specs

build(content :: term()) :: Saxy.XML.content() | [Saxy.XML.content()]

Builds content to XML content in simple form.