Rails extends Hash with from_xml
xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<foo type="integer">1</foo>
<bar type="integer">2</bar>
</hash>
XML
hash = Hash.from_xml(xml)
# => {"hash"=>{"foo"=>1, "bar"=>2}}
I'm struggling to find any examples for how to do this in Elixir in a comparably easy way.
Something like:
Map.from_xml(xml)
# => %{"hash" => %{"foo" => 1, "bar" => 2}}
I looked at sweet_xml, which has some nice sigils for pulling out specific patterns of data. My issue with it that, it requires a pretty verbose setup on my part in order to specify all the paths I would need to get.
I also looked at Quinn, which parses xml into some other data structure which can be searched. I find intermediate data structures a bit weird to work with compared to a map.
The other issue is that both these libraries use xmerl, which looks like it creates new atoms from the xml it is parsing.
I decided to scratch my own itch as an exercise to see if I could and create my first hex package: https://github.com/homanchou/elixir-xml-to-map
It uses the erlsom erlang library behind the scenes which says that it uses string keys instead, which I think is safer since atoms are not garbage collected.
Given the response to this question it's apparently extremely taboo to even consider using this naive approach, so use with caution. The Readme details the shortcomings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.