I’ve started playing around with XML in F# interactive and while F# is a joy to work with, the F# interactive sessions have two rather annoying and easily fixed deficiencies.
- XML documents are printed out as a sequence of sequences
- Printing out XML as text leaves it unformatted, i.e. the whole document is spread out on a single line
To fix this I put together the following function;
#r "System.Xml"
open System.IO
open System.Xml
open System.Text
fsi.AddPrinter(fun (xml : System.Xml.XmlNode) ->
use ms = new MemoryStream()
use w = new XmlTextWriter(ms, Encoding.Unicode)
w.Formatting <- Formatting.Indented
xml.WriteContentTo(w)
w.Flush()
ms.Flush()
ms.Position <- int64 0
use sr = new StreamReader(ms)
sr.ReadToEnd())
My initial expectation was that there would be a library function for nicely formatting XML. If there is and I haven’t found it, or if anyone knows of a better way to do this, please let me know.
Cheers,
Matt