Logo JDeck

Encoding Guide

An encoder is defined as:

type Encoder<'T> = 'T -> XmlNode

Encode provides encoders for the same primitive set as the decoders: string, boolean, char, guid, numeric widths, decimal, dateTime, dateTimeOffset, and timeSpan, plus the Exact and With format variants. Each primitive produces one text node with invariant formatting.

Build elements with Encode.element and Encode.textElement. Set attributes with Encode.attribute.

type Address = {
  street: string
  city: string
  zip: string option
} with

  static member Encoder: Encoder<Address> =
    fun address ->
      Encode.element "address" [
        Encode.textElement "street" (Encode.string address.street)
        Encode.textElement "city" (Encode.string address.city)
        match address.zip with
        | Some zip -> Encode.textElement "zip" (Encode.string zip)
        | None -> ()
      ]

type Person = { name: string; age: int; address: Address } with

  static member Encoder: Encoder<Person> =
    fun person ->
      Encode.element "person" [
        Encode.textElement "name" (Encode.string person.name)
        Encode.textElement "age" (Encode.int person.age)
        Address.Encoder person.address
      ]
      |> Encode.attribute("version", "1")
let encodedPerson = Person.Encoder person
printfn $"%s{encodedPerson.ToString()}"

The encoded node prints as one XML element with an attribute and child elements.

Collections and Maps

Encode.sequence encodes each value with an encoder for use as children. Encode.map encodes each dictionary entry as one child element.

let scores =
  Encode.element "scores" (Encode.sequence([ 1; 2; 3 ], Encode.int))

printfn $"%s{scores.ToString()}"

Encode.Null() writes an empty text node, because XML has no null literal. To emit xsi:nil, build the element and set the nil attribute on it manually.

Encoding a Full Document

The encoder for the order from the decoding guide mirrors its decoder: attributes come from Encode.attribute, repeated rows from Encode.sequence.

type Customer = { name: string; email: string option }

type Line = { sku: string; qty: int; price: decimal }

type Order = {
  id: int
  customer: Customer
  lines: Line list
  note: string option
}

let customerDecoder: Decoder<Customer> =
  fun el -> decode {
    let! name = Required.Attribute.get ("name", Required.string) el
    and! email = Optional.Element.get ("email", Required.string) el

    return { name = name; email = email }
  }

let lineDecoder: Decoder<Line> =
  fun el -> decode {
    let! sku = Required.Attribute.get ("sku", Required.string) el
    and! qty = Required.Attribute.get ("qty", Required.int) el
    and! price = Required.Attribute.get ("price", Required.decimal) el

    return { sku = sku; qty = qty; price = price }
  }

let orderDecoder: Decoder<Order> =
  fun el -> decode {
    let! id = Required.Attribute.get ("id", Required.int) el
    and! customer = Required.Element.get ("customer", customerDecoder) el
    and! lines = Required.Element.list ("lines", lineDecoder) el
    and! note = Optional.Element.get ("note", Required.string) el

    return {
      id = id
      customer = customer
      lines = lines
      note = note
    }
  }

let invariant = Globalization.CultureInfo.InvariantCulture

let encodeCustomer (customer: Customer) =
  let email =
    match customer.email with
    | Some address -> [ Encode.textElement "email" (Encode.string address) ]
    | None -> []

  Encode.element "customer" email
  |> Encode.attribute("name", customer.name)

let encodeLine (line: Line) =
  Encode.element "line" []
  |> Encode.attribute("sku", line.sku)
  |> Encode.attribute("qty", line.qty.ToString(invariant))
  |> Encode.attribute("price", line.price.ToString(invariant))

let encodeOrder (order: Order) =
  let note =
    match order.note with
    | Some text -> [ Encode.textElement "note" (Encode.string text) ]
    | None -> []

  Encode.element "order" [
    encodeCustomer order.customer
    Encode.element "lines" (Encode.sequence(order.lines, encodeLine))
    yield! note
  ]
  |> Encode.attribute("id", order.id.ToString(invariant))

let order = {
  id = 1042
  customer = { name = "Ada"; email = Some "ada@x.io" }
  lines = [
    { sku = "KB-1"; qty = 2; price = 49.90m }
    { sku = "MS-2"; qty = 1; price = 29.90m }
  ]
  note = None
}

let encodedOrder = encodeOrder order
printfn $"%s{encodedOrder.ToString()}"

A None note encodes as a missing element, and Optional.Element.get decodes both a missing child and an xsi:nil child as None, so the round trip holds. Encode.attribute takes only plain names: prefixed names such as xsi:nil fail when the node renders, so a literal nil attribute stays a manual step. This is deliberate: nil is a user decision, and the library will not guess it from an empty value.

let orderText = encodedOrder.ToString()

let roundTrip = Decoding.fromString (orderText, orderDecoder)

printfn $"Round-trip equal: %b{roundTrip = Ok order}"

Namespaces

Encode.elementNS and Encode.textElementNS build namespaced elements. The tuple is namespace URI, prefix, and local name. An empty prefix writes the namespace as the default namespace. Encode.attributeNS sets a namespaced attribute. Encode.namespaceDeclaration declares one prefix on a root element.

let feedNode =
  Encode.elementNS ("urn:shop", "s", "feed") [
    Encode.textElementNS ("urn:shop", "s", "name") (Encode.string "Shop")
    Encode.textElementNS ("urn:other", "o", "name") (Encode.string "Other")
  ]
  |> Encode.namespaceDeclaration ("o", "urn:other")
  |> Encode.attributeNS ("urn:meta", "m", "id", "7")
  |> Encode.namespaceDeclaration ("m", "urn:meta")

printfn $"%s{feedNode.ToString()}"

let feedDecoder: Decoder<string * string * int> =
  fun el -> decode {
    let! shop = Required.Element.get ("urn:shop", "name", Required.string) el
    and! other = Required.Element.get ("urn:other", "name", Required.string) el
    and! id = Required.Attribute.get ("urn:meta", "id", Required.int) el
    return shop, other, id
  }

let feedRoundTrip = Decoding.fromString (feedNode.ToString(), feedDecoder)

printfn $"Feed round-trip: %A{feedRoundTrip}"
namespace System
namespace CloudNimble
namespace CloudNimble.Text
namespace CloudNimble.Text.Xml
namespace CloudNimble.Text.Xml.Nodes
namespace JDeck
namespace JDeck.Xml
type Encoder<'T> = 'T -> XmlNode
'T
type XmlNode = override DeepClone: unit -> XmlNode member ToString: unit -> string override WriteTo: writer: Utf8XmlWriter -> unit static member Parse: xml: string -> XmlNode + 1 overload static member ParseValue: reader: byref<Utf8XmlReader> -> XmlNode member NamespaceUri: string member Parent: XmlNode member ValueKind: XmlValueKind
<summary> Defines the core behavior of a node in a mutable XML tree and provides a base for the classes that represent elements, attributes, text, CDATA sections, comments, processing instructions, and the XML declaration. </summary>
<remarks> This class is the XML counterpart of <c>JsonNode</c> in System.Text.Json. Unlike <see cref="T:CloudNimble.Text.Xml.XmlDocument" />, the tree can be changed, uses no pooled memory, and does not need to be disposed. A tree that no thread is changing can be read from several threads at once. Changes are not synchronized: while one thread changes a tree, no other thread can use it. </remarks>
Multiple items
val string: value: 'T -> string

--------------------
type string = String
type 'T option = Option<'T>
type Address = { street: string city: string zip: string option } static member Encoder: Encoder<Address>
val address: Address
module Encode from JDeck.Xml.Encoding
<summary> Provides functions for encoding values to XML nodes. All primitives format invariantly. Text values carry no type marker: XML has no native boolean, date, or null literal, so decoders parse the same lexical forms back. </summary>
val element: name: string -> children: XmlNode seq -> XmlNode
<summary> Builds an element node with the given local name and child nodes. </summary>
val textElement: name: string -> value: XmlNode -> XmlNode
<summary> Builds an element node with the given local name holding a single value node. </summary>
val string: value: string -> XmlNode
Address.street: string
Address.city: string
Address.zip: string option
union case Option.Some: Value: 'T -> Option<'T>
val zip: string
union case Option.None: Option<'T>
Multiple items
val int: value: 'T -> int (requires member op_Explicit)

--------------------
type int = int32

--------------------
type int<'Measure> = int
type Person = { name: string age: int address: Address } static member Encoder: Encoder<Person>
val person: Person
Person.name: string
val int: value: int -> XmlNode
Person.age: int
property Address.Encoder: Encoder<Address> with get
Person.address: Address
val attribute: name: string * value: string -> node: XmlNode -> XmlNode
<summary> Sets an attribute on an element node and returns the node. </summary>
val encodedPerson: XmlNode
property Person.Encoder: Encoder<Person> with get
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
XmlNode.ToString() : string
val scores: XmlNode
val sequence: values: 'T seq * encoder: Encoder<'T> -> XmlNode seq
<summary> Encodes each value, producing the sequence of child nodes. </summary>
type Customer = { name: string email: string option }
type Line = { sku: string qty: int price: decimal }
Multiple items
val decimal: value: 'T -> decimal (requires member op_Explicit)

--------------------
type decimal = Decimal

--------------------
type decimal<'Measure> = decimal
type Order = { id: int customer: Customer lines: Line list note: string option }
val id: x: 'T -> 'T
type 'T list = List<'T>
val customerDecoder: el: XmlElement -> Result<Customer,DecodeError>
type Decoder<'TResult> = XmlElement -> Result<'TResult,DecodeError>
val el: XmlElement
val decode: DecodeBuilder
val name: string
module Required from JDeck.Xml.Decode
<summary> Decoders that fail when the value is missing, nil, or has the wrong shape. </summary>
type Attribute = static member get: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>) + 3 overloads
static member Required.Attribute.get: name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Attribute.get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
static member Required.Attribute.get: namespaceUri: string * name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Attribute.get: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
val string: Decoder<string>
val email: string option
module Optional from JDeck.Xml.Decode
<summary> Decoders that return None when the value is missing or marked xsi:nil. </summary>
type Element = static member array: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult array option,DecodeError>) + 3 overloads static member dict: name: string * decoder: Decoder<'TValue> -> (XmlElement -> Result<Dictionary<string,'TValue> option,DecodeError>) + 3 overloads static member get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult option,DecodeError>) + 3 overloads static member list: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult list option,DecodeError>) + 3 overloads static member map: name: string * decoder: Decoder<'TValue> -> (XmlElement -> Result<Map<string,'TValue> option,DecodeError>) + 3 overloads static member seq: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult seq option,DecodeError>) + 3 overloads
<summary> Decodes an optional child element by local name. </summary>
static member Optional.Element.get: name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult option,DecodeError list>)
static member Optional.Element.get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult option,DecodeError>)
static member Optional.Element.get: namespaceUri: string * name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult option,DecodeError list>)
static member Optional.Element.get: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult option,DecodeError>)
val lineDecoder: el: XmlElement -> Result<Line,DecodeError>
val sku: string
val qty: int
val int: Decoder<int>
val price: decimal
val decimal: Decoder<decimal>
val orderDecoder: el: XmlElement -> Result<Order,DecodeError>
val id: int
val customer: Customer
type Element = static member array: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult array,DecodeError>) + 3 overloads static member dict: name: string * decoder: Decoder<'TValue> -> (XmlElement -> Result<Dictionary<string,'TValue>,DecodeError>) + 3 overloads static member get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>) + 3 overloads static member list: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult list,DecodeError>) + 3 overloads static member map: name: string * decoder: Decoder<'TValue> -> (XmlElement -> Result<Map<string,'TValue>,DecodeError>) + 3 overloads static member seq: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult seq,DecodeError>) + 3 overloads
<summary> Decodes a required child element by local name. Attributes hold scalars only; there are no sequence attributes. </summary>
static member Required.Element.get: name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Element.get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
static member Required.Element.get: namespaceUri: string * name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Element.get: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
val lines: Line list
static member Required.Element.list: name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult list,DecodeError list>)
static member Required.Element.list: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult list,DecodeError>)
static member Required.Element.list: namespaceUri: string * name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult list,DecodeError list>)
static member Required.Element.list: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult list,DecodeError>)
val note: string option
val invariant: Globalization.CultureInfo
namespace System.Globalization
Multiple items
type CultureInfo = interface ICloneable interface IFormatProvider new: culture: int -> unit + 3 overloads member ClearCachedData: unit -> unit member Clone: unit -> obj member Equals: value: obj -> bool member GetConsoleFallbackUICulture: unit -> CultureInfo member GetFormat: formatType: Type -> obj member GetHashCode: unit -> int member ToString: unit -> string ...
<summary>Provides information about a specific culture (called a locale for unmanaged code development). The information includes the names for the culture, the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.</summary>

--------------------
Globalization.CultureInfo(culture: int) : Globalization.CultureInfo
Globalization.CultureInfo(name: string) : Globalization.CultureInfo
Globalization.CultureInfo(culture: int, useUserOverride: bool) : Globalization.CultureInfo
Globalization.CultureInfo(name: string, useUserOverride: bool) : Globalization.CultureInfo
property Globalization.CultureInfo.InvariantCulture: Globalization.CultureInfo with get
<summary>Gets the <see cref="T:System.Globalization.CultureInfo" /> object that is culture-independent (invariant).</summary>
<returns>The object that is culture-independent (invariant).</returns>
val encodeCustomer: customer: Customer -> XmlNode
val email: XmlNode list
Customer.email: string option
val address: string
Customer.name: string
val encodeLine: line: Line -> XmlNode
val line: Line
Line.sku: string
Line.qty: int
Int32.ToString() : string
Int32.ToString( format: string) : string
Int32.ToString(provider: IFormatProvider) : string
Int32.ToString( format: string, provider: IFormatProvider) : string
Line.price: decimal
Decimal.ToString() : string
Decimal.ToString( format: string) : string
Decimal.ToString(provider: IFormatProvider) : string
Decimal.ToString( format: string, provider: IFormatProvider) : string
val encodeOrder: order: Order -> XmlNode
val order: Order
val note: XmlNode list
Order.note: string option
val text: string
Order.customer: Customer
Order.lines: Line list
Order.id: int
val encodedOrder: XmlNode
val orderText: string
val roundTrip: Result<Order,DecodeError>
type Decoding = static member auto: value: string -> Result<'TResult,DecodeError> + 2 overloads static member autoWithOptions: value: string * options: XmlSerializerOptions -> Result<'TResult,DecodeError> + 2 overloads static member fromBytes: value: byte array * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromBytesCol: value: byte array * decoder: CollectErrorsDecoder<'TResult> -> Result<'TResult,DecodeError list> static member fromElement: element: XmlElement * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromStream: value: Stream * decoder: Decoder<'TResult> -> Task<Result<'TResult,DecodeError>> static member fromStreamCol: value: Stream * decoder: CollectErrorsDecoder<'TResult> -> Task<Result<'TResult,DecodeError list>> static member fromString: value: string * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromStringCol: value: string * decoder: CollectErrorsDecoder<'TResult> -> Result<'TResult,DecodeError list>
<summary> Entry points that parse XML text and run a decoder on the document element. </summary>
static member Decoding.fromString: value: string * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError>
union case Result.Ok: ResultValue: 'T -> Result<'T,'TError>
val feedNode: XmlNode
val elementNS: namespaceUri: string * prefix: string * name: string -> children: XmlNode seq -> XmlNode
<summary> Builds an element node in one namespace. An empty prefix writes the default namespace. </summary>
val textElementNS: namespaceUri: string * prefix: string * name: string -> value: XmlNode -> XmlNode
<summary> Builds an element node in one namespace holding a single value node. </summary>
val namespaceDeclaration: prefix: string * namespaceUri: string -> node: XmlNode -> XmlNode
<summary> Declares one namespace prefix on an element node and returns the node. </summary>
val attributeNS: namespaceUri: string * prefix: string * name: string * value: string -> node: XmlNode -> XmlNode
<summary> Sets a namespaced attribute on an element node and returns the node. </summary>
val feedDecoder: el: XmlElement -> Result<(string * string * int),DecodeError>
val shop: string
val other: string
val feedRoundTrip: Result<(string * string * int),DecodeError>

Type something to start searching.