将seq <recordtype>转换为xml?</recordtype>

时间:2013-12-06 19:11:21

标签: f# f#-3.0

记录类型

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

如何将其转换为Xml字符串?

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

返回

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

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

或者它可以是一个可以处理任何记录类型的通用函数吗?

2 个答案:

答案 0 :(得分:2)

您可以使用CLIMutableAttribute修饰记录,以允许XmlSerializer对其进行处理。此外,我不确定序列化seq,但我使用了数组

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()

答案 1 :(得分:1)

使用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))))

通过使用运算符或函数包装一些方法调用,可以缩短这一点。例如,使用这两个辅助函数:

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

它更清洁:

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 ] ]