Bodu.Text.Yaml Namespace
- Package
-
Bodu.Text.Yaml 1.0.0
Purpose
Bodu.Text.Yaml is a YAML library for .NET 8. It maps plain CLR objects to and from YAML through a configurable converter model, over a buffered token reader and a forward-only writer, with both a mutable and a read-only document object model.
The library is the third member of the Bodu serializer family, alongside Bodu.Text.Toml and Bodu.Text.Bencode. It shares the family's architecture - a static serializer façade, a low-level reader/writer pair, a mutable DOM, and a read-only DOM - but tunes the serializer surface to YAML and exposes YAML's richer presentation model. The types are organised into folders/namespaces by surface (Reader, Writer, Document, Nodes, Serialization).
Bodu.Text.Yaml implements the Bodu YAML Core Tree Profile: a YAML 1.2 core-schema, JSON-compatible tree model. Mapping keys resolve to unique scalar strings, anchors are unique and acyclic, and tabs are rejected as indentation. It supports block and flow collections, quoted and block scalars, comments, anchors and aliases, opt-in YAML 1.1 merge keys, core tags, and multi-document streams. The reader is buffered - it parses into an in-memory node store rather than scanning in a single pass. For EditorConfig-style INI configuration, see Bodu.Text.Ini; for binary-to-text encodings (Base16 / Base32 / Base64 / Base58 / Base85), see the companion Bodu.Text.Encoding package.
Static documentation
- Bodu serializers introduction - the three libraries, the shared tiers, and how to choose a format.
- Bodu.Text.Yaml introduction - what is specific to YAML: the value model, presentation, multi-document streams, and diagnostics.
- Core concepts - the serializer, the converter model, the two DOMs, and the reader/writer seam.
- Getting started - install and the first round trip.
- Using YAML - type mapping, spec-version selection, the DOMs, and multi-document streams.
- Writing converters - custom shapes with
YamlConverter<T>.
Key types
Serializer (Bodu.Text.Yaml)
- YamlSerializer - static façade.
Serializeto astring(from a typed value or anobject+Type) or anIBufferWriter<byte>,SerializeAsyncto aStream;Deserialize<T>from astring, a UTF-8ReadOnlySpan<byte>, or aStream, andDeserializeAsync<T>from aStream. The stream overloads are buffered in full - only the stream copy is asynchronous. - YamlSerializerOptions - naming policy, converters,
IncludeFields,DefaultIgnoreCondition,WriteEnumsAsStrings,PropertyNameCaseInsensitive,SpecVersion,NumberHandling,DuplicateKeyBehavior,MergeKeyBehavior,UnmappedMemberHandling,PreferredObjectCreationHandling, andMaxDepth; constructed plain or from a YamlSerializerDefaults preset (General/Web); cached and frozen on first use. - NamingPolicy - camel, snake (lower/upper), and kebab (lower/upper) casing policies.
- YamlTokenType, YamlValueKind - the token and value-kind enumerations.
- YamlSpecVersion - the spec selector:
V1_2(default core schema) orV1_1(addsyes/no/on/offbooleans and sexagesimal numbers). YamlNumberHandling - float-to-integer coercion. YamlScalarStyle - the plain / quoted / literal / folded scalar styles. YamlBlockChomping - block-scalar trailing-newline handling. YamlDuplicateKeyBehavior, YamlMergeKeyBehavior, UnmappedMemberHandling - mapping-key policies. - YamlFormatException - malformed input (with line / column / offset). YamlSerializationException - binding failures (with offset and member path).
Low-level reader / writer
- Utf8YamlReader (+ YamlReaderOptions) - forward-only, buffered token reader over parsed YAML.
- Utf8YamlWriter (+ YamlWriterOptions) - forward-only token writer; emits block-style YAML with configurable indentation.
Document object models
- YamlNode / YamlObject / YamlArray / YamlValue - the mutable, editable DOM.
- YamlDocument / YamlElement / YamlProperty - the read-only, low-allocation DOM;
ParseAllDocumentsreturns every document in a multi-document stream (parsing tuned by YamlDocumentOptions).
Converters and attributes (Bodu.Text.Yaml.Serialization)
- YamlConverter<T> / YamlConverter / YamlConverterFactory - base types for custom per-type converters and converter factories; a converter reads through the Utf8YamlReader and writes through the Utf8YamlWriter.
- YamlStringEnumConverter (+
YamlStringEnumConverter<TEnum>) andYamlNumberEnumConverter<TEnum>- the public enum converters: member-name strings (with optional naming policy) or the underlying numeric value. - PropertyNameAttribute, IgnoreAttribute, ConverterAttribute, and the wider shared attribute family (
[PropertyOrder],[Required],[Include],[ExtensionData],[Constructor],[ObjectCreationHandling],[NamingPolicy],[StringEnumMemberName]) - the declarative member-shaping layer.
Example
using Bodu.Text.Yaml;
public sealed class ServerConfig
{
public string Host { get; set; } = "";
public int Port { get; set; }
}
string yaml = YamlSerializer.Serialize(new ServerConfig { Host = "localhost", Port = 8080 });
ServerConfig config = YamlSerializer.Deserialize<ServerConfig>(yaml)!;
// Edit a document without a model:
using Bodu.Text.Yaml.Nodes;
YamlNode node = YamlNode.Parse(yamlText)!;
node["server"]!["port"] = YamlValue.Create(9090);
string back = node.ToYamlString();
Notes
- Shared serialization core. The library references Bodu.Text.Serialization for the attribute family, the naming policies, the ignore / creation / unmapped-member enums, and the serialization callback interfaces, and compiles that package's shared metadata resolver and converter engine under its own format symbol - the same arrangement as its siblings Bodu.Text.Toml and Bodu.Text.Bencode. The reader, writer, DOMs, and scalar converters are format-local.
- Full family serializer surface. Member shaping is covered by the naming policies, the shared
Bodu.Text.Serializationattribute family, the serialization callback interfaces, the options flags, and customYamlConverter<T>converters andYamlConverterFactoryfactories - the same surface as the TOML and Bencode siblings. YAML's scalar converters remain format-local so implicit typing coerces across scalar kinds. - Value mapping.
string/char/Guid/Uriand the integer family → string or integer scalars,double/float→ float scalars,bool→ boolean,null→ the null scalar; enums → member-name strings (or integers whenWriteEnumsAsStringsisfalse). Collections map to sequences; dictionaries and objects map to mappings in insertion order. Anobject-typed member reads back as a loosely-typed graph (Dictionary<string, object?>/List<object?>/ scalars); members typed YamlNode or YamlElement bind through the DOM bridges. Public fields participate viaIncludeFields. - Presentation is resolved, not stored. Scalar style (plain / quoted / literal / folded), block vs. flow layout, and anchors and aliases are handled by the reader and chosen by the writer rather than surfaced as distinct value kinds; ScalarStyle records the original scalar style.
- Spec-version selection. Parsing defaults to the strict 1.2 core schema (only
true/falseare booleans); settingSpecVersiontoV1_1additionally acceptsyes/no/on/offbooleans and sexagesimal numbers, and the%YAMLdirective overrides typing per document. - Multi-document streams.
YamlDocument.ParseAllDocumentsreturns every document delimited by---/...; the single-document methods read the first. - Errors. Malformed input surfaces through YamlFormatException (with line, column, and offset); binding failures through YamlSerializationException (with offset and a dotted member path).
- See also: the introduction, core concepts, and getting-started; the Using YAML and writing converters guides; and the sibling TOML and Bencode libraries.
Namespaces
Classes
- YamlFormatException
Represents an error that occurs when YAML data is malformed or violates the YAML specification.
- YamlSerializationException
The exception thrown when a value cannot be bound to or from a YAML document during serialization - for example a type mismatch, a missing required member, or a value YAML cannot represent.
- YamlSerializer
Provides static methods to serialize objects to YAML and deserialize YAML to objects, in the manner of System.Text.Json.JsonSerializer.
- YamlSerializerOptions
Provides options that configure YamlSerializer, in the manner of JsonSerializerOptions.
Enums
- YamlBlockChomping
Specifies how trailing line breaks are handled in a block scalar (the literal
|or folded>styles), corresponding to the chomping indicator in the block scalar header.
- YamlDuplicateKeyBehavior
Specifies how the reader and document layers treat a mapping that declares the same key more than once.
- YamlMergeKeyBehavior
Specifies how the reader treats the YAML merge key (
<<).
- YamlNumberHandling
Specifies how YamlSerializer coerces numeric scalars when binding to integral targets.
- YamlScalarStyle
Specifies the presentation style of a YAML scalar node. The style controls how a scalar's content is delimited and escaped when emitted, and records how it was delimited when read.
- YamlSerializerDefaults
Specifies a base set of defaults applied when a YamlSerializerOptions instance is created for a particular usage scenario.
- YamlSpecVersion
Identifies the version of the YAML specification whose implicit type resolution the reader applies. The version controls how unquoted (plain) scalars are interpreted as booleans, null, and numbers.
- YamlTokenType
Identifies the kind of token surfaced by Utf8YamlReader as it traverses a YAML document in document order.
- YamlValueKind
Specifies the resolved kind of a YAML node, as surfaced by the document object models after implicit type resolution has been applied to scalars.