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 :-).
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).
The followings are nice resources which I encountered, while I was experimenting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With