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}"
<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>
val string: value: 'T -> string
--------------------
type string = String
<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>
<summary> Builds an element node with the given local name and child nodes. </summary>
<summary> Builds an element node with the given local name holding a single value node. </summary>
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int
<summary> Sets an attribute on an element node and returns the node. </summary>
<summary> Encodes each value, producing the sequence of child nodes. </summary>
val decimal: value: 'T -> decimal (requires member op_Explicit)
--------------------
type decimal = Decimal
--------------------
type decimal<'Measure> = decimal
<summary> Decoders that fail when the value is missing, nil, or has the wrong shape. </summary>
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>)
<summary> Decoders that return None when the value is missing or marked xsi:nil. </summary>
<summary> Decodes an optional child element by local name. </summary>
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>)
<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: 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>)
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>)
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
<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>
Int32.ToString( format: string) : string
Int32.ToString(provider: IFormatProvider) : string
Int32.ToString( format: string, provider: IFormatProvider) : string
Decimal.ToString( format: string) : string
Decimal.ToString(provider: IFormatProvider) : string
Decimal.ToString( format: string, provider: IFormatProvider) : string
<summary> Entry points that parse XML text and run a decoder on the document element. </summary>
<summary> Builds an element node in one namespace. An empty prefix writes the default namespace. </summary>
<summary> Builds an element node in one namespace holding a single value node. </summary>
<summary> Declares one namespace prefix on an element node and returns the node. </summary>
<summary> Sets a namespaced attribute on an element node and returns the node. </summary>
JDeck