Question

For record type of

type ARecordType = { Aaa: string; Bbb: string; Id: int; Ccc: string }

How to convert it to an Xml string?

let recordTypeToXml (recordType: seq<ARecordType>) =
    .....

returns

<Root><Row><Aaa>...</Aaa>...</Row>.....</Root>

or

<Root><Row @Aaa="..." @Bbb="..." ... />....</Root>

Or can it be a generic function that can handle any record type?

Was it helpful?

Solution 2

This is straightforward using Linq to Xml:

let recordTypeToXml (recordType: seq<ARecordType>) = 
  XElement(XName.Get "Root",
    recordType |> Seq.map (fun {Aaa=a; Bbb=b; Ccc=c} ->
      XElement(XName.Get "Row",
        XAttribute(XName.Get "Aaa", a),
        XAttribute(XName.Get "Bbb", b),
        XAttribute(XName.Get "Ccc", c))))

You can shorten this a bit by wrapping some of the method calls with operators or functions. For example, with these two helper functions:

let Element name (content: seq<_>) = XElement(XName.Get name, content)
let Attr name value = XAttribute(XName.Get name, value)

it's much cleaner:

let recordTypeToXml (recordType: seq<ARecordType>) = 
  Element "Root"
    [ for {Aaa=a; Bbb=b; Ccc=c} in recordType ->
        Element "Row" 
          [ Attr "Aaa" a
            Attr "Bbb" b
            Attr "Ccc" c ] ]

OTHER TIPS

You can decorate the record with CLIMutableAttribute to allow XmlSerializer to work on it. Also I'm not sure about serializing seq, but I got it working with an array

open System.Xml.Serialization
open System.IO

[<CLIMutable>]
type ARecordType = { Aaa: string; Bbb: string; Id: int; Ccc: string }

let recordTypeToXml (recordType: ARecordType []) =
    let xmlSer = XmlSerializer(typeof<ARecordType []>)
    use ms = new MemoryStream()
    xmlSer.Serialize(ms, Array.ofSeq recordType)
    ms.Seek(0L, SeekOrigin.Begin) |> ignore

    use sr = new StreamReader(ms)
    sr.ReadToEnd()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top