Logo JDeck

Decoding Guide

JDeck.Xml mirrors the JDeck decoding API over XmlElement instead of JsonElement.

Automatic Decoding

let myobj =
  Decoding.auto<MyType>("<MyType><id>a1b2c3d4</id></MyType>")

A decoder is defined as:

type Decoder<'TResult> = XmlElement -> Result<'TResult, DecodeError>

Where XmlElement is the immutable cursor into an XmlDocument. Use Required decoders when a value must exist and must parse. Use Optional decoders when a child or attribute can be missing or xsi:nil. Use VOptional decoders for the same cases with voption results.

Available Decoders

Both Required and Optional provide the same primitive set:

XML has two named channels, so navigation splits in two:

Decoding XML Objects

type Person = {
  name: string
  age: int
  email: string option
}

let objectDecoder: Decoder<Person> =
  fun el -> decode {
    let! name = Required.Element.get ("name", Required.string) el
    and! age = Required.Element.get ("age", Required.int) el
    and! email = Optional.Element.get ("email", Required.string) el

    return { name = name; age = age; email = email }
  }

let personResult =
  Decoding.fromString(
    "<person><name>Ada</name><age>36</age></person>",
    objectDecoder
  )

printfn $"Person: %A{personResult}"

Attributes decode through the same primitive decoders:

let idResult =
  Decoding.fromString(
    "<person id=\"7\"><name>Ada</name></person>",
    Required.Attribute.get("id", Required.int)
  )

printfn $"Id: %A{idResult}"

Decoding Discriminated Unions

Use Decode.oneOf when one element can hold several shapes.

type Shape =
  | Circle of float
  | Square of float

let shapeDecoder: Decoder<Shape> =
  Decode.oneOf [
    fun el -> decode {
      let! r = Required.Element.get ("Circle", Required.float) el
      return Circle r
    }
    fun el -> decode {
      let! s = Required.Element.get ("Square", Required.float) el
      return Square s
    }
  ]

let shapeResult =
  Decoding.fromString("<shape><Circle>1.5</Circle></shape>", shapeDecoder)

printfn $"Shape: %A{shapeResult}"

Entry Points

Decoding a Full Document

Real documents mix both channels: the order id is an attribute, the customer mixes an attribute with a child element, each line carries only attributes, and a missing note arrives as xsi:nil. One decoder composes all of them:

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 orderXml =
  """<order id="1042"><customer name="Ada"><email>ada@x.io</email></customer><lines><line sku="KB-1" qty="2" price="49.90"/><line sku="MS-2" qty="1" price="29.90"/></lines><note xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/></order>"""

let orderResult = Decoding.fromString (orderXml, orderDecoder)

printfn $"Order: %A{orderResult}"

Required.Element.list reads the <lines> wrapper and decodes each <line> child from its attributes. Optional.Element.get maps both a missing child and an xsi:nil child to None, so note decodes to None here.

Namespaces

Namespaces are part of an XML element identity. Two elements can share one local name in different namespaces. The namespace-aware overloads take the namespace URI first. They match that URI exactly. An empty URI matches an element or attribute in no namespace.

let shopNs = "urn:shop"
let otherNs = "urn:other"

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

let feedResult =
  Decoding.fromString(
    """<feed xmlns:s="urn:shop" xmlns:o="urn:other"><s:name>Shop</s:name><o:name>Other</o:name></feed>""",
    feedDecoder
  )

printfn $"Namespaced names: %A{feedResult}"

The same overload set exists on Optional.Element and VOptional.Element. It also exists on Required.Attribute, Optional.Attribute, and VOptional.Attribute. Attributes need one rule: an unprefixed attribute is in no namespace. Pass an empty URI for it. A prefixed attribute carries the URI its prefix binds to.

Decode.decodeAtKeyInNamespace and Decode.tryDecodeAtKeyInNamespace give the same exact match without a wrapper type.

The local-name overloads stay available. They match any namespace. Use them only when the document has one vocabulary. The order decoder from this guide does that:

let namespacedResult =
  Decoding.fromString(
    """<order xmlns="urn:shop" id="1042"><customer name="Ada"><email>ada@x.io</email></customer><lines><line sku="KB-1" qty="2" price="49.90"/></lines></order>""",
    orderDecoder
  )

printfn $"Namespaced order: %A{namespacedResult}"
namespace CloudNimble
namespace CloudNimble.Text
namespace CloudNimble.Text.Xml
namespace JDeck
namespace JDeck.Xml
type MyType = { id: string }
val id: x: 'T -> 'T
Multiple items
val string: value: 'T -> string

--------------------
type string = System.String
val myobj: Result<MyType,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.auto: value: System.IO.Stream -> System.Threading.Tasks.Task<Result<'TResult,DecodeError>>
static member Decoding.auto: value: byte array -> Result<'TResult,DecodeError>
static member Decoding.auto: value: string -> Result<'TResult,DecodeError>
type Decoder<'TResult> = XmlElement -> Result<'TResult,DecodeError>
type XmlElement = member CloneNode: unit -> XmlNode member EnumerateAttributes: unit -> AttributeEnumerator member EnumerateChildren: unit -> Enumerator member Equals: other: XmlElement -> bool + 1 overload member GetAttribute: localName: string -> XmlElement + 3 overloads member GetBoolean: unit -> bool member GetByte: unit -> byte member GetBytesFromBase64: unit -> byte array member GetChild: localName: string -> XmlElement + 3 overloads member GetDateTime: unit -> DateTime ...
<summary> Represents a specific XML node within an <see cref="T:CloudNimble.Text.Xml.XmlDocument" />. </summary>
<example><code> using var document = XmlDocument.Parse("&lt;catalog&gt;&lt;item id=\"1\"&gt;&lt;qty&gt;3&lt;/qty&gt;&lt;/item&gt;&lt;/catalog&gt;"u8); foreach (var item in document.RootElement.EnumerateChildren()) { var id = item.GetAttribute("id").GetInt32(); var qty = item.GetChild("qty").GetInt32(); } </code></example>
<remarks> This struct is the XML counterpart of <c>JsonElement</c> in System.Text.Json. A value can represent an element, an attribute, a text node, a CDATA section, a comment, or a processing instruction; <see cref="P:CloudNimble.Text.Xml.XmlElement.ValueKind" /> tells which. A value is usable only while its parent <see cref="T:CloudNimble.Text.Xml.XmlDocument" /> is not disposed. The value of an attribute, a text node, a CDATA section, a comment, or a processing instruction is its content. The value of an element is the text of all text nodes and CDATA sections inside it, in document order. The typed getters, such as <see cref="M:CloudNimble.Text.Xml.XmlElement.GetInt32" />, ignore leading and trailing white space in the value. Name lookups, enumeration, the numeric and Boolean getters, and <see cref="M:CloudNimble.Text.Xml.XmlElement.WriteTo(CloudNimble.Text.Xml.Utf8XmlWriter)" /> do not allocate. Members that return a <see cref="T:System.String" />, a <see cref="T:byte[]" />, or an <see cref="T:CloudNimble.Text.Xml.Nodes.XmlNode" /> allocate only that result, except <see cref="M:CloudNimble.Text.Xml.XmlElement.GetRawXml" />, which also allocates the buffer and the writer it writes the markup with. </remarks>
Multiple items
module Result from Microsoft.FSharp.Core

--------------------
type Result<'T,'TError> = | Ok of ResultValue: 'T | Error of ErrorValue: 'TError
Multiple items
module DecodeError from JDeck.Xml

--------------------
type DecodeError = { value: XmlElement kind: XmlValueKind rawValue: string targetType: Type message: string exn: exn option index: int option property: string option attribute: string option }
<summary> In case of failure when a type is being decoded, this type contains the relevant information about the error. </summary>
type Person = { name: string age: int email: string option }
Multiple items
val int: value: 'T -> int (requires member op_Explicit)

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

--------------------
type int<'Measure> = int
type 'T option = Option<'T>
val objectDecoder: el: XmlElement -> Result<Person,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 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 string: Decoder<string>
val age: int
val int: Decoder<int>
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 personResult: Result<Person,DecodeError>
static member Decoding.fromString: value: string * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError>
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
val idResult: Result<int,DecodeError>
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>)
type Shape = | Circle of float | Square of float
Multiple items
val float: value: 'T -> float (requires member op_Explicit)

--------------------
type float = System.Double

--------------------
type float<'Measure> = float
val shapeDecoder: Decoder<Shape>
Multiple items
module Decode from JDeck.Xml.Decode

--------------------
module Decode from JDeck.Xml
val oneOf: decoders: Decoder<'TResult> seq -> Decoder<'TResult>
<summary> Tries each decoder in order and returns the first success, otherwise the first error. </summary>
val r: float
val float: Decoder<float>
union case Shape.Circle: float -> Shape
val s: float
union case Shape.Square: float -> Shape
val shapeResult: Result<Shape,DecodeError>
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 = System.Decimal

--------------------
type decimal<'Measure> = decimal
type Order = { id: int customer: Customer lines: Line list note: string option }
type 'T list = List<'T>
val customerDecoder: el: XmlElement -> Result<Customer,DecodeError>
val lineDecoder: el: XmlElement -> Result<Line,DecodeError>
val sku: string
val qty: int
val price: decimal
val decimal: Decoder<decimal>
val orderDecoder: el: XmlElement -> Result<Order,DecodeError>
val id: int
val customer: Customer
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 orderXml: string
val orderResult: Result<Order,DecodeError>
val shopNs: string
val otherNs: string
val feedDecoder: el: XmlElement -> Result<(string * string),DecodeError>
val shop: string
val other: string
val feedResult: Result<(string * string),DecodeError>
val namespacedResult: Result<Order,DecodeError>

Type something to start searching.