0

I receive the following exception during deserialzation

Exception: There is an error in XML document (0, 0). Inner Exception: Root element is missing.

But as far as I can see the XML file looks pretty valid to me, I even used an validator to verify it. And at this moment i didn't find any solution or the problem, I am also new to C# development.

<?xml version="1.0" encoding="utf-8"?>
<ListOfShows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <list>
    <ShowData>
      <UniqueId>0</UniqueId>
      <Title>MoinMoin</Title>
      <Subtitle>Montags bis Freitags | 10.30 Uhr | LIVE | #moinmoin</Subtitle>
      <Description>Die Bohnen wünschen einen guten Morgen aus dem #moinmoin-Studio in Hamburg. Was steht in der Zeitung? Wie schmeckt der Kaffee? Habt ihr gut geschlafen? Diese und andere lebenswichtige Fragen beantworten euch die immer gut gelaunten Moderatoren von Rocket Beans TV.</Description>
      <ImagePath>C:\Users\Simon\AppData\Local\Packages\a7251417-49a0-4960-845d-9227b525e0c1_ggxdvrfmnj0tt\moinmoin.png</ImagePath>
      <Content>Die Bohnen wünschen einen guten Morgen aus dem #moinmoin-Studio in Hamburg. Was steht in der Zeitung? Wie schmeckt der Kaffee? Habt ihr gut geschlafen? Diese und andere lebenswichtige Fragen beantworten euch die immer gut gelaunten Moderatoren von Rocket Beans TV.</Content>
    </ShowData>
    <ShowData>
      <UniqueId>1</UniqueId>
      <Title>Bohn Jour</Title>
      <Subtitle>Mittwochs | 20.15 Uhr | LIVE | #bohnjour</Subtitle>
      <Description>Dieses sympathische Plausch und Show-Format ist Dreh- und Angelpunkt der Rocketbeanschen Woche. Unsere Bohnen manövrieren mit euch durch News, Gewinnspiele und allerhand Themen der Internetwelt, die sonst sicher zu kurz gekommen wären. Dazu gibt’s eine Band und Gäste... wenn sie sich trauen!</Description>
      <ImagePath>C:\Users\Simon\AppData\Local\Packages\a7251417-49a0-4960-845d-9227b525e0c1_ggxdvrfmnj0tt\bohnjour.png</ImagePath>
      <Content>Dieses sympathische Plausch und Show-Format ist Dreh- und Angelpunkt der Rocketbeanschen Woche. Unsere Bohnen manövrieren mit euch durch News, Gewinnspiele und allerhand Themen der Internetwelt, die sonst sicher zu kurz gekommen wären. Dazu gibt’s eine Band und Gäste... wenn sie sich trauen!</Content>
    </ShowData>
    <ShowData>
      <UniqueId>2</UniqueId>
      <Title>Almost Daily</Title>
      <Subtitle>Dienstags und Samstags | 20.15 Uhr | #almostdaily</Subtitle>
      <Description>Das Talkformat mit dem goldenen Tisch! Willkommen bei Almost Daily. Hier werden Themen ohne Tabus besprochen und Unterhaltsam aufbereitet. Eine Punchline jagt die nächste und wenn es um flotte Sprüche geht, dann macht unseren Jungs niemand etwas vor. Coole Konzepte und interessante Gäste. Die #1 Video-Talkrunde auf Twitch.</Description>
      <ImagePath>C:\Users\Simon\AppData\Local\Packages\a7251417-49a0-4960-845d-9227b525e0c1_ggxdvrfmnj0tt\almostdaily.png</ImagePath>
      <Content>Das Talkformat mit dem goldenen Tisch! Willkommen bei Almost Daily. Hier werden Themen ohne Tabus besprochen und Unterhaltsam aufbereitet. Eine Punchline jagt die nächste und wenn es um flotte Sprüche geht, dann macht unseren Jungs niemand etwas vor. Coole Konzepte und interessante Gäste. Die #1 Video-Talkrunde auf Twitch.</Content>
    </ShowData>
    <ShowData>
      <UniqueId>3</UniqueId>
      <Title>Kino+</Title>
      <Subtitle>Donnerstags | 20.15 Uhr | #kinoplus</Subtitle>
      <Description>Donnerstag ist Kino-Tag! Das bedeutet es ist wieder Zeit für Kino+. Hier bekommt ihr aktuelle Filmstarts, Trailer und News. Und wenn ihr Glück habt, haben wir auch was zu verlosen! Also holt euch euer Popcorn, schnappt euch ein Kaltgetränk eurer Wahl und lehnt euch zurück. Die Vorstellung geht gleich los.</Description>
      <ImagePath>C:\Users\Simon\AppData\Local\Packages\a7251417-49a0-4960-845d-9227b525e0c1_ggxdvrfmnj0tt\kinoplus.png</ImagePath>
      <Content>Donnerstag ist Kino-Tag! Das bedeutet es ist wieder Zeit für Kino+. Hier bekommt ihr aktuelle Filmstarts, Trailer und News. Und wenn ihr Glück habt, haben wir auch was zu verlosen! Also holt euch euer Popcorn, schnappt euch ein Kaltgetränk eurer Wahl und lehnt euch zurück. Die Vorstellung geht gleich los.</Content>
    </ShowData>
  </list>
</ListOfShows>

I used the following classes for the serialization. The ListOfShows class which contains several ShowData.

public class ListOfShows
{
    public List<ShowData> list { get; set; }
    public ListOfShows()
    {
        list = new List<ShowData>();
    }

    public XDocument generateXMLDocument()
    {
        var xml = new XDocument();
        using (var writer = xml.CreateWriter())
        {
            var serializer = new XmlSerializer(typeof(ListOfShows));
            serializer.Serialize(writer, this);
        }
        return xml;
    }
}

public class ShowData
{

    public ShowData()
    {

    }

    public string UniqueId { get; set; }
    public string Title { get; set; }
    public string Subtitle { get; set; }
    public string Description { get; set; }
    public string ImagePath { get; set; }
    public string Content { get; set; }
}

And this is the method where I do de-serializiton:

    static public async Task<ListOfShows> readStoredShows()
    {
        String fileName = "storedShow.xml";
        StorageFile file;
        ListOfShows shows = null;
        try
        {
            file = await file = await home.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
        }
        catch (FileNotFoundException ex)
        {
            Debug.WriteLine(ex.Message);
            file = null;
        }
        catch (UnauthorizedAccessException ex)
        {
            Debug.WriteLine(ex.Message);
            file = null;
        }
        if (file != null)
        {
            try
            {
                IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
                readStream.Seek(0);
                using (StreamReader reader = new StreamReader(readStream.AsStream()))
                {
                    reader.DiscardBufferedData();
                    Debug.WriteLine("Reader:" + reader.ReadToEnd());
                    var serializer = new XmlSerializer(typeof(ListOfShows));
                    shows = serializer.Deserialize(reader) as ListOfShows;
                }
            }
            catch (InvalidOperationException ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
                Debug.WriteLine("Inner Exception: " +  ex.InnerException.Message);
            }
        }
        else
        {
            Debug.WriteLine("Ein Fehler ist während des Ladens aufgetreten");
        }
        return shows;
    }

Hope someone can help me find my problem.

Best Greetings

Templum
  • 183
  • 1
  • 12
  • Sounds like `XmlSerializer` starts deserializing, but not from the beginning of stream. Is there *rewind* option or anything like this in your stream? – Sinatr Jul 01 '15 at 12:24
  • I could use the seek(ulong) method of IRandomAccessStream, which would set the position of the stream to the specified value. Did you mean something like this ? – Templum Jul 01 '15 at 12:30
  • Try to do it before calling `Deserialize`. – Sinatr Jul 01 '15 at 12:35
  • I called the method directly after assigning readStream. Outcome is the same, still the exception. – Templum Jul 01 '15 at 12:38
  • The file is valid. I just deserialized this from a file. So it's a problem with the stream. Because you are using `IRandomAccessStream` I guess you are working with databases. Check whether the stream connects correctly to your database. – Andy Jul 01 '15 at 12:48
  • Try to [rewind StreamReader](http://stackoverflow.com/q/2053206/1997232). – Sinatr Jul 01 '15 at 12:48
  • @Andy your right I tried the readToEnd() method of reader and its string is empty. I modified my post and included now the way how I load the file. Which is stored in local appdata. – Templum Jul 01 '15 at 13:13
  • Are you developing a windows app or a usual desktop application? – Andy Jul 01 '15 at 13:31
  • You are overwriting the existing file with the `CreateFileAsync` method. The file will always be empty. I guess that's the problem. Comment that line and try again. And replace the empty file with a correct xml file of course. – Andy Jul 01 '15 at 13:42
  • @Andy what a shameful mistake of mine. I modified the code an replaced the CreateFileAsync method through GetFileAsync. Now its works. Thanks so much – Templum Jul 01 '15 at 13:56
  • I'm glad about that. I posted it as an answer. Oh, you shouldn't edit your post to the correct version because then other people will be confused :) – Andy Jul 01 '15 at 14:04

2 Answers2

1

You are always creating a new file by mistake in readStoredShows:

file = await home.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

You only want to read the existing one:

file = await home.GetFileAsync(fileName);
Andy
  • 3,997
  • 2
  • 19
  • 39
0

I changed your code a bit and it worked. Hope this helps if you are not worried to use different mechanism other than IRandomAccessStream. By the way [Serializable] attribute missing in your code.

using System;
using System.Collections.Generic;
using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ListOfShows));
            StreamReader reader = new StreamReader(@"C:\Raj\Learn\TestConsole\TestConsole\XMLFile1.xml"); //Give path of the file.
            var listOfShows = (ListOfShows)serializer.Deserialize(reader);
            reader.Close();
        }
    }

    [Serializable]
    public class ListOfShows
    {

        public List<ShowData> list { get; set; }
        public ListOfShows()
        {
            list = new List<ShowData>();
        }

        public XDocument generateXMLDocument()
        {
            var xml = new XDocument();
            using (var writer = xml.CreateWriter())
            {
                var serializer = new XmlSerializer(typeof(ListOfShows));
                serializer.Serialize(writer, this);
            }
            return xml;
        }
    }

    [Serializable]
    public class ShowData
    {
        public ShowData()
        {
        }
        public string UniqueId { get; set; }
        public string Title { get; set; }
        public string Subtitle { get; set; }
        public string Description { get; set; }
        public string ImagePath { get; set; }
        public string Content { get; set; }
    }
}
Raj Karri
  • 551
  • 4
  • 19