2

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.

Brains
  • 594
  • 1
  • 6
  • 18
  • try removing second instance of "---" on line 5 – RyanCJI Dec 15 '14 at 18:42
  • 1
    It does support multiple documents using the YamlStream class. However, I suspect the deserializer is only expecting one document. It is not clear from your question what you are trying to achieve with two documents. – Darrel Miller Dec 15 '14 at 21:17

1 Answers1

1

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

Antoine Aubry
  • 12,203
  • 10
  • 45
  • 74