Cfdi.Xml.Element (cfdi_xml v4.0.1)

Copy Markdown

Declarative XML element schema — Ecto-style DSL for CFDI elements.

Define an element's attributes, namespaces, and XML tag in one module. The macro generates:

  • defstruct with all declared fields (default nil)
  • @type t with attribute types
  • to_element/1 (and to_element/2 for elements that accept children) that serializes to an XmlBuilder tuple
  • __xml__/1 introspection helpers (:tag, :attributes, :children, :namespaces)

Example

defmodule Cfdi.Emisor do
  use Cfdi.Xml.Element, tag: "cfdi:Emisor"

  attribute :Rfc, :string
  attribute :Nombre, :string
  attribute :RegimenFiscal, :string
  attribute :FacAtrAdquirente, :string
end

Now you can do:

%Cfdi.Emisor{Rfc: "AAA010101AAA", Nombre: "ACME"}
|> Cfdi.Emisor.to_element()
#=> {"cfdi:Emisor", %{"Rfc" => "AAA010101AAA", "Nombre" => "ACME"}, nil}

Namespaces (root element)

defmodule Cfdi.Comprobante do
  use Cfdi.Xml.Element, tag: "cfdi:Comprobante", accepts_children: true

  xmlns :cfdi, "http://www.sat.gob.mx/cfd/4"
  xmlns :xsi, "http://www.w3.org/2001/XMLSchema-instance"

  attribute :Version, :string
  # ...
end

When accepts_children: true is set, to_element/2 is defined with a second argument for nested XML tuples.

Children fields (not serialized as attributes)

Some CFDI elements have fields that represent nested structures rather than XML attributes (e.g. Concepto holds a list of impuestos). Use child instead of attribute:

defmodule Cfdi.Concepto do
  use Cfdi.Xml.Element, tag: "cfdi:Concepto"

  attribute :ClaveProdServ, :string
  # ...
  child :impuestos, :list
  child :informacion_aduanera, :list
end

Children appear in the struct and @type t but are not serialized to XML attributes in the auto-generated to_element/1 — callers render them explicitly.

Summary

Functions

Declares an XML attribute on the element.

Declares a nested-structure field that is NOT serialized as an attribute.

Declares a namespace (xmlns:prefix="uri") for the element. Typically used on root elements only.

Functions

attribute(name, type, opts \\ [])

(macro)

Declares an XML attribute on the element.

child(name, type)

(macro)

Declares a nested-structure field that is NOT serialized as an attribute.

xmlns(prefix, uri)

(macro)

Declares a namespace (xmlns:prefix="uri") for the element. Typically used on root elements only.