Heya,
I’m trying to use SweetXml to parse an XML like this one:
<?xml version="1.0"?>
<lecturers>
<lecturer>
<key>75A7EBE3323C0EB1</key>
<firstName>Albert</firstName>
<lastName>Einstein</lastName>
</lecturer>
<lecturer>
<key>619D3EDCF60E5A14</key>
<firstName>Niels</firstName>
<lastName>Bohr</lastName>
</lecturer>
</lecturers>
… and I would like to get a list of mappings in return. Now, I actually already found a way to do so, but it seems needlessly complicated:
iex(26)> ls = """
...(26)> <?xml version="1.0"?>
...(26)> <lecturers>
...(26)> <lecturer>
...(26)> <key>75A7EBE3323C0EB1</key>
...(26)> <firstName>Albert</firstName>
...(26)> <lastName>Einstein</lastName>
...(26)> </lecturer>
...(26)> <lecturer>
...(26)> <key>619D3EDCF60E5A14</key>
...(26)> <firstName>Niels</firstName>
...(26)> <lastName>Bohr</lastName>
...(26)> </lecturer>
...(26)> </lecturers>
...(26)> """
"<?xml version=\"1.0\"?>\n<lecturers>\n <lecturer>\n <key>75A7EBE3323C0EB1</key>\n <firstName>Albert</firstName>\n <lastName>Einstein</lastName>\n </lecturer>\n <lecturer>\n <key>619D3EDCF60E5A14</key>\n <firstName>Niels</firstName>\n <lastName>Bohr</lastName>\n </lecturer>\n</lecturers>\n"
iex(27)> ls |> xpath(~x"/lecturers/lecturer"l, key: ~x"./key/text()"s, firstName: ~x"./firstName/text()"s, lastName: ~x"./lastName/text()"s)
[
%{key: "75A7EBE3323C0EB1", firstName: "Albert", lastName: "Einstein"},
%{key: "619D3EDCF60E5A14", firstName: "Niels", lastName: "Bohr"}
]
For every key/node, I have to specify it twice, and verbosely so (~x"./…/text()"s
is a handful), while ideally I would like to do something like dwim(ls, ~x"/lecturers/lecturer"l, [:key, :firstName, :lastName])
.
Am I just holding SweetXml wrong? Its documentation wasn’t really helpful to me, and I’m also a very novice Elixir programmer, so maybe I’m just overlooking something trivial.
Thanks!