2

I’d like to write a Haskell library to work with a web service API. I get an XML or JSON response from the server, say it looks like this:

<foo>
    <bar>1</bar>
    <baz>moo</baz>
</foo>

I want to turn it into a record:

data Foo = Foo {
    bar :: Integer,
    baz :: String
}

How can I abstract this so that I don’t have to manually parse the XML and pick the individual components by hand? I hoped for an API that would let me describe the mapping from the XML elements and attributes to the record parts and do the rest for me.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • Do you have a DOCTYPE or XML Schema for the API? –  Jan 01 '13 at 10:24
  • I don’t think so. Would it help? I wouldn’t mind writing it, but I’m afraid it would be mork work than writing the parsing code by hand. – zoul Jan 01 '13 at 10:35
  • 1
    It's actually necessary to know what types of data you expect in order to turn it into any data type (so also for records). It doesn't matter how you use it: you could hardcode it into a hand-written parser (as you're planning to do), or generate a parser from an XML Schema (using `XsdToHaskell` from [HaXml](http://hackage.haskell.org/package/HaXml), for instance). –  Jan 01 '13 at 10:40
  • In the current absence of more specifi advice, you could look at [this question about which XML library to use](http://stackoverflow.com/questions/1361307/which-haskell-xml-library-to-use) for now. – AndrewC Jan 01 '13 at 10:45
  • @Tinctorius: Didn’t know about `XsdToHaskell`, will take a look, thank you. I know I would have to specify the data types, I was hoping I could simply pass a “deserialization” filter function to be applied to the attribute or element in question. – zoul Jan 01 '13 at 10:46
  • Another approach is using Template Haskell to automatically generate the code to "pick the individual components". –  Jan 02 '13 at 16:28

0 Answers0