EctoXml (ecto_xml v1.0.1) View Source

Provides functions to generate XML documents based on Ecto Schemas and maps.

It uses XmlBuilder under the hood, see: https://github.com/joshnuss/xml_builder.

Link to this section Summary

Functions

Generates a partial XML element based on one ecto schema or map.

Generates a XML document based on one ecto schema or map.

Link to this section Functions

Link to this function

to_partial_xml(data, options \\ [])

View Source

Specs

to_partial_xml(map(), list()) :: String.t()

Generates a partial XML element based on one ecto schema or map.

The behaviour is idential to to_xml/3, except that it does not generate the XML document (e.g. <?xml version=X encoding=Y?>) with a root element name (e.g. <root> content </root>), generating only the partial element instead.

Example

The following:

%{foo: "bar"} |> EctoXml.to_partial_xml()

Results in:

<foo>bar</foo>

Check to_xml/3 for more examples and use cases.

Link to this function

to_xml(data, document_name, options \\ [])

View Source

Specs

to_xml(map(), atom(), list()) :: String.t()

Generates a XML document based on one ecto schema or map.

The document_name argument refers to the XML root element name.

Generating XML from maps

The following:

%{foo: "bar"} |> EctoXml.to_xml(:root, format: :none)

Results in:

<?xml version="1.0" encoding="UTF-8"?><root><foo>bar</foo></root>

Generating XML from an Ecto Schema

For a given schema:

defmodule Person do
  @moduledoc false

  use Ecto.Schema

  @primary_key false

  embedded_schema do
    field :name, :string
  end
end

The following:

%Person{name: "Foo Bar"} |> EctoXml.to_xml(:person, format: :none)

Results in:

<?xml version="1.0" encoding="UTF-8"?><person><name>Foo Bar</name></person>

Customizing field names

For a given schema:

defmodule Person do
  @moduledoc false

  use Ecto.Schema

  @primary_key false

  @derive {
    EctoXml.Builder,
    map_field_names: %{
      :name => :custom_element_name
    }
  }

  embedded_schema do
    field :name, :string
  end
end

The following:

%Person{name: "Foo Bar"} |> EctoXml.to_xml(:person, format: :none)

Results in:

<?xml version="1.0" encoding="UTF-8"?><person><custom_element_name>Foo Bar</custom_element_name></person>