I'm new to Clojure and would like to convert an XML I have into an edn object.
The XML file I reads:
<Vehicle>
<Model>Toyota</Model>
<Color>Red</Color>
<Loans>
<Reoccuring>Monthly</Reoccuring>
<Owners>
<Owner>Bob</Owner>
</Owners>
</Loans>
<Tires>
<Model>123123</Model>
<Size>23</Size>
</Tires>
<Engine>
<Model>30065</Model>
</Engine>
</Vehicle>
And I have saved it as 'test/resources/vehicle.xml
Ultimately, I would like to have a EDN object that looks like:
:Vehicle
:Model "Toyota"
:Color "Red"
:Loans
:Reoccuring "Monthly"
:Owners
:Owner "Bob"
:Tires
:Model 123123
:Size 23
:Engine
:Model 30065
So far, what I have tried in Clojure is the parse method:
(def xml-parser
(parse "<Vehicle><Model>Toyota</Model><Color>Red</Color><Loans><Reoccuring>Monthly</Reoccuring><Owners><Owner>Bob</Owner></Owners></Loans><Tires><Model>123123</Model><Size>23</Size></Tires><Engine><Model>30065</Model></Engine></Vehicle>"))
However, this returns a Clojure hash that looks like:
{:tag :Vehicle, :attrs nil, :content [{:tag :Model, :attrs nil, :content ["Toyota"]} {:tag :Color, :attrs nil, :content ["Red"]} {:tag :Loans, :attrs nil, :content [{:tag :Reoccuring, :attrs nil, :content ["Monthly"]} {:tag :Owners, :attrs nil, :content [{:tag :Owner, :attrs nil, :content ["Bob"]}]}]} {:tag :Tires, :attrs nil, :content [{:tag :Model, :attrs nil, :content ["123123"]} {:tag :Size, :attrs nil, :content ["23"]}]} {:tag :Engine, :attrs nil, :content [{:tag :Model, :attrs nil, :content ["30065"]}]}]}
I'm having trouble with this initial step of conversion. Thank you for your help in advance.
The data you have is in Enlive format. Use
clojure.pprint/pprintto see a nicer format:The problem is that your desired output is not actually legal EDN data format. However, you can use the
tupelo.forestlibrary to convert among several data formats:First declare the data and parse it into Enlive format:
verify the result
convert to Hiccup format:
You may also like the "bush" format:
or the more detailed "tree" format
See the Tupelo Forest docs for full information.
The above code was run using this template project.
If you are looking for a hierarchical map style output, you can kludge together something like so:
with test
Although this is pretty fragile as written.