dailyprice

dailyprice

Parsing XML key/value pairs with \"key\":"\value\" synyax

I am new to Elixir, but love what I am seeing so far! I would think Elixir would be a great suit for my query below given the pattern matching capabilities, but at my current level I am stuck.

My issue is as follows: I am trying to parse a list of key:value pairs from an XML file. I have included the first couple of pairs below.

["\"ClassNotationDocumentUrl\":\"\",\"VesselId\":\"40775\",\"IMONo\":\"9866718\",\"Currentname\":\"LOWLANDS CRIMSON\",\"VesselGuid\":\"a5379088-2c7d-42d8-bdf5-c5677ce5c1d2\",

I am struggling to figure out how to parse this into an Elixir struct, could anyone point me in the right direction?

Many thanks for your help!

Most Liked

stevensonmt

stevensonmt

Can’t provide a good example right now on phone but look at nimbleparsec package on hex. It’s brilliant for parsing all sorts of input.

al2o3cr

al2o3cr

This is one approach to get started; see below for notes about why it’s brittle:

iex(20)> Regex.scan(~r/"([^"]*)":"([^"]*)",?/, s, capture: :all_but_first)
[
  ["ClassNotationDocumentUrl", ""],
  ["VesselId", "40775"],
  ["IMONo", "9866718"],
  ["Currentname", "LOWLANDS CRIMSON"],
  ["VesselGuid", "a5379088-2c7d-42d8-bdf5-c5677ce5c1d2"]
]

The brittleness of this solution is from subexpressions like [^"]* - if the data ever contains " characters as part of a value this parser will break, as it doesn’t implement any kind of escaping.

APB9785

APB9785

Creator of ECSx

I usually do something like this:

Enum.reduce(input_list, %{}, fn item, acc ->
  [key, value] =
    item
    |> String.replace("\"", "")
    |> String.split(":")

  Map.put(acc, key, value)
end)

For each item in the list, get rid of the quotation marks, split at the colon, and then put them into a map (or struct if the keys are always the same). Note how Elixir’s pattern matching allows us to easily assign key and value variables from the result of the pipeline.

Where Next?

Popular in Questions Top

logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement