Loading XML to Elixir Converter...
Please wait a moment

How to Convert XML to Elixir Structs

Step 1

Paste or Upload Your XML

Paste XML into the left editor, upload an .xml or .txt file, or press Sample to load a worked example.

Example XML

<?xml version="1.0" encoding="UTF-8"?>
<phoenix-app name="ChatApp" version="1.4.2">
  <application>
    <name>chat_app</name>
    <elixir-version>1.14.0</elixir-version>
    <is-umbrella>false</is-umbrella>
  </application>
  <dependencies>
    <dependency>phoenix</dependency>
    <dependency>phoenix_live_view</dependency>
  </dependencies>
  <database>
    <host>localhost</host>
    <port>5432</port>
    <pool-size>10</pool-size>
  </database>
</phoenix-app>
Step 2

Let It Read the Structure

The Elixir output updates as you type. Every element and attribute is looked at, including all copies of repeated elements. Broken XML shows the line and column of the first problem instead of code.

•
Structs: one defstruct per element with children or attributes, with a @type t typespec
•
XML reading: from_xml/1 and parse/1 built on :xmerl, which comes with Erlang/OTP
•
Types: integer(), float(), boolean() or String.t(), chosen from every value in your document
•
Plain maps: to_map/1 turns the structs into maps for JSON encoding
Step 3

Check the Generated Structs

Look over the module names, fields and typespecs. The original XML names stay in the reading code, so the Elixir names can follow Elixir conventions.

Elixir output for the example

This is the module for the root element. The file also has modules for application, dependencies and database, and ends with the XmlData.Xml reading helpers:

defmodule XmlData.PhoenixApp do
  @moduledoc "Struct for the <phoenix-app> element."
  alias XmlData.Xml

  @type t :: %__MODULE__{
          name: String.t() | nil, # attribute name
          version: String.t() | nil, # attribute version
          application: XmlData.Application.t() | nil,
          dependencies: XmlData.Dependencies.t() | nil,
          database: XmlData.Database.t() | nil
        }

  defstruct [
    name: nil,
    version: nil,
    application: nil,
    dependencies: nil,
    database: nil
  ]

  @doc "Reads an XML document (a UTF-8 string) into this struct."
  @spec parse(String.t()) :: t()
  def parse(xml) when is_binary(xml), do: xml |> Xml.parse_string() |> from_xml()

  @doc "Builds the struct from an :xmerl <phoenix-app> element."
  @spec from_xml(tuple() | nil) :: t() | nil
  def from_xml(nil), do: nil

  def from_xml(el) do
    %__MODULE__{
      name: Xml.attr(el, "name", nil),
      version: Xml.attr(el, "version", nil),
      application: el |> Xml.child("application", nil) |> XmlData.Application.from_xml(),
      dependencies: el |> Xml.child("dependencies", nil) |> XmlData.Dependencies.from_xml(),
      database: el |> Xml.child("database", nil) |> XmlData.Database.from_xml()
    }
  end

  @doc "Turns the struct into plain maps."
  @spec to_map(t()) :: map()
  def to_map(%__MODULE__{} = struct), do: Xml.to_map(struct)
end
Step 4

Copy or Download the File

Copy the code or download it as xml_structs.ex, put it in your project's lib folder, add :xmerl to extra_applications and read documents with the root module's parse function.

•
Copy to clipboard and paste into your project
•
Download xml_structs.ex and rename the XmlData prefix if your app uses its own namespace
•
Pass the data on from a Phoenix controller or LiveView, using to_map/1 when you need JSON

What is XML to Elixir Conversion?

It means writing Elixir structs that match the shape of an XML document, so the rest of your code can pattern match on %PhoenixApp{} fields instead of digging through :xmerl tuples. Doing that by hand gets old quickly once a document has a few levels of nesting and some repeated elements.

This converter looks at the whole document, merges every copy of each element, and writes a struct for each element that has children or attributes. Each struct gets a from_xml function that reads the document with :xmerl, and to_map/1 for when you want to pass the data on as JSON.

Frequently Asked Questions

What does the generated Elixir file contain?

One module for each XML element that has child elements or attributes, all under XmlData, so an <application> element becomes XmlData.Application and never clashes with Elixir's own Application module. Each module has a defstruct, a @type t, a from_xml/1 function that reads an :xmerl element and a to_map/1 function. The module for the root element also gets parse/1, which takes the XML as a string. A small XmlData.Xml module at the end of the file does the actual reading.

How are the field types chosen?

From the text of every value the element has in your document. Whole numbers become integer() at any size, because Elixir integers have no upper limit, so an ID like 8901240544102066246 comes back with every digit. Numbers with a decimal point become float() (14.50 is read as the float 14.5), and only the exact words true and false become boolean(). Values with leading zeros such as 00501, hex like 0x1F, elements that are sometimes empty and anything mixed stay String.t(), because reading them as numbers would change or drop data.

How do I read an XML file with these structs?

The code uses :xmerl, which ships with Erlang/OTP, so no Hex packages are needed. In a Mix project, add :xmerl to extra_applications in mix.exs, then call the root module's parse function, for example XmlData.PhoenixApp.parse(File.read!("data.xml")). Child elements are matched by local name and namespace, attributes and text (CDATA included) are read directly, and a value that does not read as its type becomes nil instead of raising. The output was checked by compiling it with Elixir 1.14 on OTP 25 with warnings treated as errors and reading each test document back. :xmerl turns element names into atoms, so be careful about feeding it large numbers of documents you don't control.

Can I use the structs with Phoenix, Jason or Ecto?

to_map/1 turns a struct, and the structs inside it, into plain maps, which Jason.encode!/1 and Phoenix JSON views accept as they are, so the file compiles without Jason as a dependency. The structs are not Ecto schemas. If you want to store the data, copy the fields into your own schema or changeset.

What happens with repeated elements and different copies of the same element?

All copies of an element name are merged before any code is written. A field that only appears in the second <dependency> still makes it into the struct, and if a value is a number in one copy and text in another, the field becomes String.t(). An element that appears more than once under the same parent becomes a list that defaults to []; one that appears once defaults to nil.

How are XML names turned into Elixir names?

Fields use snake_case (pool-size becomes pool_size) and modules use PascalCase. Words Elixir reserves get a _value suffix (an <end> element becomes end_value), names that start with a digit get a field_ prefix, and clashes, such as an attribute and a child both called id, are numbered (id_2). Module names have to be ASCII, so accents are dropped and names in other scripts fall back to a generic name. The original XML name is still what the code looks for when reading.

Is my XML uploaded anywhere?

No. The conversion runs in your browser, and the XML you paste or upload is not sent to our server.