Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing xml with xmerl

Tags:

xml

elixir

I'm trying to parse a xml structure like this

<result>
  <event>
    <title>My event</name>
    <artist>
      <name>Michael Jackson</name>
    </artist>
  </event>
  <event>
    <title>My event 2</name>
    <artist>
      <name>Rolling Stones</name>
    </artist>
  </event>
<result>

So i want to traverse the events, and end up with a Elixir map with the corresponding result. It needs to be name agnostic, as the fields on the events my differ.

The desired result

[{title: “My event”, artist: [{name: “Michael Jackson”}]}, {title: “My even 2t”, artist: [{name: “Rolling stones"}]}]

So this is what i got so far

defmodule Test do

  require Record
  require IEx
  Record.defrecord :xmlElement, Record.extract(:xmlElement, from_lib: "xmerl/include/xmerl.hrl")
  Record.defrecord :xmlText, Record.extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")

  def run do
    {root, _} = :xmerl_scan.file("test.xml")

    event_elements = :xmerl_xpath.string('//event', root)

    # Traverse each event.
    fields = Enum.map event_elements, fn(event) ->

      # Traverse each field.
      Enum.map event, fn(field) ->
        [xmlElement(field, :name), xmlText(field, :value)]
      end
    end
  end
end

Test.run

I'm very new to Elixir, and i couldn't find any propper guide to xmerl. I hope someone can help me, and please do explain the code :-).

like image 676
MartinElvar Avatar asked Dec 24 '22 21:12

MartinElvar


1 Answers

I'm not so familiar with xmerl, but the following is my trial based on your example (it's not complete and rough, but hope it helps some).

  • https://gist.github.com/parroty/7f96bc11474e9bab38b2

The followings are nice resources which I encountered, while I was experimenting.

  • https://gist.github.com/sasa1977/5967224
  • https://gist.github.com/devinus/2726bbce531adae8e260
like image 170
parroty Avatar answered Jan 02 '23 00:01

parroty