F#中的XML序列化

6

我是一个完全的F#新手,所以希望我提供足够的信息。我创建了一个名为record的类。我使用来自数据库的数据创建了该类的几个实例。然后我将每个记录添加到记录列表中。我想用这些记录创建一个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>)

运行时我遇到了以下错误信息:

反射类型'Microsoft.FSharp.Collections.FSharpList`1[XXXX.Compliance.YYYYY.record]'时出错。 //这里的x和y是为了保护隐私。

1个回答

4
注意:我不确定。
我认为一些 F# 类型(如 'list')不能使用 XmlSerializer 进行序列化(例如,该序列化技术需要具有字段设置器或公共默认构造函数等等)。一些可能立即解决问题的选项包括:
  • 从使用 F# 列表更改为使用 .NET 数组(record list -> record [] 等)
  • (可能)使用 DataContractSerializer 替代 XmlSerializer,因为 DCS 不需要类型具备太多要求(我忘记它是否适用于 F# 列表)
  • 可能还有其他我忘记的方法
希望对 .NET 序列化技术更熟悉的人能提供更明确的答案。

1
我认为你是对的。我把所有东西都改成了数组而不是列表。看起来已经解决了问题。 - Ramy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接