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:
- Text and boolean:
string,boolean,char,guid,unit - Numeric:
byte,sbyte,int16,uint16,int,uint32,int64,uint64,single,float,decimal - Date and time:
dateTime,dateTimeOffset,timeSpan, plusdateTimeExact,dateTimeOffsetExact, andtimeSpanExact
XML has two named channels, so navigation splits in two:
Required.Element.get/Optional.Element.getread child elementsRequired.Attribute.get/Optional.Attribute.getread attributesElement.seq,Element.list,Element.array,Element.map, andElement.dictread collections and maps from one child element
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.fromStringparses text, then runs a decoder on the root element.Decoding.fromBytesandDecoding.fromStreamdo the same for bytes and streams.Decoding.fromStringColcollects every error instead of the first one.Decoding.autodelegates toXmlSerializerfor plain records.
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}"
val string: value: 'T -> string
--------------------
type string = System.String
<summary> Entry points that parse XML text and run a decoder on the document element. </summary>
static member Decoding.auto: value: byte array -> Result<'TResult,DecodeError>
static member Decoding.auto: value: string -> Result<'TResult,DecodeError>
<summary> Represents a specific XML node within an <see cref="T:CloudNimble.Text.Xml.XmlDocument" />. </summary>
<example><code> using var document = XmlDocument.Parse("<catalog><item id=\"1\"><qty>3</qty></item></catalog>"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>
module Result from Microsoft.FSharp.Core
--------------------
type Result<'T,'TError> = | Ok of ResultValue: 'T | Error of ErrorValue: 'TError
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>
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int
<summary> Decoders that fail when the value is missing, nil, or has the wrong shape. </summary>
<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>)
<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>)
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 float: value: 'T -> float (requires member op_Explicit)
--------------------
type float = System.Double
--------------------
type float<'Measure> = float
module Decode from JDeck.Xml.Decode
--------------------
module Decode from JDeck.Xml
<summary> Tries each decoder in order and returns the first success, otherwise the first error. </summary>
val decimal: value: 'T -> decimal (requires member op_Explicit)
--------------------
type decimal = System.Decimal
--------------------
type decimal<'Measure> = decimal
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>)
JDeck