Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Xml TypeProvider for C#

Is there an equivalent to the F# TypeProvider in C#? I am looking at the easiest way to read an Xml file with C#. At this point I am planning to use XDocument, but I was wondering if there was something better.

F# makes it so easy to read an Xml file that I wonder if I shouldn't switch language for Xml processing!

like image 367
Martin Avatar asked Dec 16 '22 07:12

Martin


1 Answers

As already mentioned, C# does not support type providers and there is no easy way for emulating them (as Gustavo mentioned, you could use generated type providers through a small F# library, but XML, JSON, CSV and others are not this kind.)

I think using F# library that does the processing is the best approach.

A more complicated alternative would be to write code that lets you define types to model the XML file in C# and then automatically reads the file into these classes. I do not think anything like this exists, but I wrote a similar thing in F# (before type providers), so you can see the snippet for inspiration. The usage looks like this:

// Modelling RSS feeds - the following types define the structure of the
// expected XML file. The StructuralXml parser can automatically read
// XML file into a structure formed by these types.
type Title = Title of string
type Link = Link of string
type Description = Description of string

type Item = Item of Title * Link * Description
type Channel = Channel of Title * Link * Description * list<Item>
type Rss = Rss of Channel

// Load data and specify that names in XML are all lowercase
let url = "http://feeds.guardian.co.uk/theguardian/world/rss"
let doc : StructuralXml<Rss> = 
  StructuralXml.Load(url, LowerCase = true)

// Match the data against a type modeling the RSS feed structure
let (Rss(channel)) = doc.Root
let (Channel(_, _, _, items)) = channel
for (Item(Title t, _, _)) in items do
  printfn "%s" t
like image 143
Tomas Petricek Avatar answered Dec 18 '22 12:12

Tomas Petricek