Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read XML in F#?

Tags:

f#

xmlreader

I wonder what reading XML with XmlReader would look like in a idiomatic functional style. Namely how XmlReader as a stateful entity is supposed to be treated. Is there a good example?

like image 378
Trident D'Gao Avatar asked Mar 22 '23 23:03

Trident D'Gao


1 Answers

I would say that XmlReader is a good choice if you need to process a large XML document without reading the whole document in memory (i.e. stream processing). It is not particularly functional, but that's perfectly fine - when doing I/O in F#, you do not need to write that in a functional way, because that's always tricky with I/O (not impossible, but F# users just tend to use standard .NET libraries).

If your file fits in memory, and has fairly regular structure, than the XML type provider mentioned by John is the best option. When calling the provider, you can give it a sample XML file, the provider infers the structure and you can read XML in a nice typed way.

If you have an irregular file with complex structure (something like XHTML) then I'd use the XDocument type (which has a more modern API than XmlDocument and can be used quite easily from F#).

like image 51
Tomas Petricek Avatar answered Mar 31 '23 06:03

Tomas Petricek