Today I Learned

A Hashrocket project

Transform values when using SweetXML xmap

Assume I have the following XML


xml = """
<response>
  <users>
    <user>
      <firstName>Micah</firstName>
      <lastName>Cooper</lastName>
    </user>
    <user>
      <firstName>Joe</firstName>
      <lastName>Hashrocket</lastName>
    </user>
 </users>
</response>
"""

I can write a small module to map this to something really cool.

defmodule XmlMapper do
  import SweetXml
  @schema [
      names: [ ~x[//response/users/user]l,
        name: ~x[concat(./firstName, " ", ./lastName)]s |> transform_by(&String.upcase/1)
      ]
    ]

  def map(xml_string) do
    SweetXml.xmap(xml_string, @schema)
  end
end

.map will find a list of user elements, concatenate the firstName and lastName, then upcase the whole thing and return it in a map.

iex> XmlMapper.map(xml)
%{names: [%{name: "MICAH COOPER"}, %{name: "JOE HASHROCKET"}]}

That’s doing a lot with a little.

Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.