Does YamlDotNet library support the document separator?

1.6k views Asked by At

This YAML file:

---
- Prisoner
- Goblet
- Phoenix
---
- Memoirs
- Snow 
- Ghost

is deserializing by this code:

var input = new StreamReader (path)
var deserializer = new Deserializer();
var lis = deserializer.Deserialize <List <string>> (input);

Result is Exception in YamlDotNet.dll:

(Line: 5, Col: 4, Idx: 136): Expected 'StreamEnd', 
got 'DocumentStart' (at Line: 5, Col: 1, Idx: 133).

Update1: SharpYaml: the same exception

Update2: @DarrelMiller: Yes, it is not clear from my first example, but the need of document separator is seen in second example:

---
- Prisoner
- Goblet
- Phoenix
---
- Memoirs: [213, 2004]
- Snow: [521, 2011] 
- Ghost: [211, 2002]

So I needed the separator to change the type for the Deserializer.

@AntoineAubry: Thanks for answer and YamlDotNet, I like them both.

1

There are 1 answers

2
Antoine Aubry On BEST ANSWER

You can easily deserialize more than one document. In order to do that, you need to use the Deserialize() overload that takes an EventReader:

public void Main()
{
    var input = new StringReader(Document);

    var deserializer = new Deserializer();

    var reader = new Parser(input);

    // Consume the stream start event "manually"
    reader.Consume<StreamStart>();

    // Deserialize the first document
    var firstSet = deserializer.Deserialize<List<string>>(reader);

    Console.WriteLine("## First document");
    foreach(var item in firstSet)
    {
        Console.WriteLine(item);
    }

    // Deserialize the second document
    var secondSet = deserializer.Deserialize<List<string>>(reader);

    Console.WriteLine("## Second document");
    foreach(var item in secondSet)
    {
        Console.WriteLine(item);
    }   
}

Here's a fully working example.

You can even read any number of documents by using a loop:

while(reader.Accept<DocumentStart>())
{
    // Deserialize the document
    var doc = deserializer.Deserialize<List<string>>(reader);

    Console.WriteLine("## Document");
    foreach(var item in doc)
    {
        Console.WriteLine(item);
    }
}

Working example