简体   繁体   中英

C# Error while deserialize using XmlSerializer in Windows Store App

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

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);

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; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM