Sax.Builder protocol (sax v1.0.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 - fields to be encoded as attributes.
  • children - fields to be encoded as element children.

Examples

defmodule Person do
  @derive {Sax.Builder, name: "person", attributes: [:gender], children: [:name]}

  defstruct [:name, :gender]
end

iex> person = %Person{name: "Alice", gender: "female"}
iex> Sax.Builder.build(person)
{"person", [{"gender", "female"}], [{:characters, "Alice"}]}

Custom implementation could be done by implementing protocol:

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

defimpl Sax.Builder do
  import Sax.XML

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

iex> user = %User{name: "Alice", username: "alice99"}
iex> Sax.Builder.build(user)
{"Person", [{"userName", "alice99"}], [{"Name", [], [characters: "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()) :: Sax.XML.content()

Builds content to XML content in simple form.