Serialization XMLSerializer选项字段
以下f#脚本未序列化选项字段:Serialization XMLSerializer选项字段,serialization,f#,Serialization,F#,以下f#脚本未序列化选项字段: open System.Xml.Serialization [<CLIMutable>] type Repo = { [<XmlElement("mandatory")>] mandatory : string [<XmlElement("optional", IsNullable=true)>] optional : string option } with sta
open System.Xml.Serialization
[<CLIMutable>]
type Repo = {
[<XmlElement("mandatory")>] mandatory : string
[<XmlElement("optional", IsNullable=true)>] optional : string option
}
with
static member serialize data (filename: string) =
let writer = System.Xml.Serialization.XmlSerializer(data.GetType())
use file = new System.IO.StreamWriter(filename)
writer.Serialize(file, data)
let x = { mandatory = "insert text"; optional = Some("optional text") }
Repo.serialize x @"d:\tmp\prova.xml"
open System.Xml.Serialization
[]
类型Repo={
[]必填项:字符串
[]可选:字符串选项
}
具有
静态成员序列化数据(文件名:字符串)=
让writer=System.Xml.Serialization.XmlSerializer(data.GetType())
使用file=new System.IO.StreamWriter(文件名)
序列化(文件、数据)
设x={mandatory=“insert text”;optional=Some(“optional text”)}
Repo.serialize x@“d:\tmp\prova.xml”
结果xml文件为:
<?xml version="1.0" encoding="utf-8"?>
<Repo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<mandatory>insert text</mandatory>
<optional />
</Repo>
插入文本
为什么“optional”元素为空?很可能XmlSerializer不知道选项类型或记录。您已指定IsNullable。因此,要么使用null或string,要么尝试其他XMLSerializer。因此,答案是我无法使用XMLSerializer来序列化选项字段,对吗?这可能是我的猜测,但我可能是错的,因此给出了注释。如果您需要选项类型,我将探索XML类型提供程序、FSpickler或DataContractSerializer。例如,FSpickler为我提供了以下输出:
optional>text1