使用F#进行XML序列化

Ram*_*amy 5 xml f# xml-serialization

我总共是F#n00b,所以希望我能给您足够的信息。我创建了一个称为记录的类。我使用数据库中的数据创建该类的几个实例。然后,我将每个记录添加到记录列表中。我想用这些记录制作一个xml文档。

//this is the record data type i created. I also created a sender and recipient data
//type but those are probably not neccessary to understand the issue
type record(id:int, sender:sender, ?recipients: recipient list ) =  
    let mutable id: int = id
    let mutable typ = "Message"
    let mutable creation = creation()
    let mutable sender  = sender
    let mutable recipients = recipients

    [<XmlIgnore()>] 
    [<XmlArrayAttribute("recipients")>]
    [<XmlArrayItem(typeof<recipient>, ElementName = "recipient")>]
    member this.Recipients with get() = recipients and set v = recipients <- v

    public new() =
        record(12180, sender(12180,"Joe","Plumber","Joe@plumber.com"), list.Empty)

    [<XmlElement("id")>] 
    member this.Id with get() = id and set v = id <- v

    [<XmlElement("creation")>] 
    member this.Creation with get() = creation and set v = creation <- v

    [<XmlElement("sender")>] 
    member this.Sender with get() = sender and set v = sender <- v

//i later call this:
 let xmlSerializer = XmlSerializer(typeof<record list>)
Run Code Online (Sandbox Code Playgroud)

然后,我在运行时收到此错误消息:

发生错误,反映了类型'Microsoft.FSharp.Collections.FSharpList`1 [XXXX.Compliance.YYYYY.record]'。// x和y用于保护无辜者。

Bri*_*ian 4

警告:我不确定。

我认为某些 F# 类型(如“列表”)不允许使用 XmlSerializer 进行序列化(例如,序列化技术需要具有字段设置器或公共默认构造函数或一些此类废话的类型)。我认为一些可能会立即解锁您的选项包括

  • 从使用 F# 列表更改为使用 .NET 数组(record list->record []等)
  • (可能)使用DataContractSerializer代替XmlSerializer,因为 DCS 不需要太多类型(我忘记它是否适用于 F# 列表)
  • 可能还有其他我忘记的事情

希望其他更熟悉 .NET 序列化技术的人可以提供更明确的答案。