Search code examples
c#xnaisolatedstorage

Error on XML Document (4,11)


currently i'm developing window game which using isolate storage to process the information. I'm trying to do it in XML however i meet this problem while trying to generate XML document and read it from it. Here's the code and XML generated.

Part of code:

using(IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAssembly())
{
    using(IsolatedStorageFileStream stream =
      new IsolatedStorageFileStream("class.xml", FileMode.Create, file))
    {
        XmlWriterSettings setting = new XmlWriterSettings();
        setting.Indent = true;
        using(XmlWriter writer = XmlWriter.Create(stream, setting))
        {
            XmlSerializer serializer = new XmlSerializer(typeof (Student));
            serializer.Serialize(stream, new Student()
            {
                Name = "AhLim"
            });
        }
    }

    using(IsolatedStorageFileStream stream =
      new IsolatedStorageFileStream("class.xml", FileMode.Open, file))
    {
        XmlSerializer serializer = new XmlSerializer(typeof (Student));
        studentA = (Student) serializer.Deserialize(stream);
    }
}

The Student class:

public class Student
{
    public String Name { get; set; }
}

The generated XML document :

<?xml version="1.0"?>
<Student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <Name>AhLim</Name>
</Student>

After all, the error as title, XML document error at (4,11) occur on deserialization. I cant figure out the problem as i googled and know the stream issue. Thanks for your all's help


Solution

  • Its because you are writing the xml using the IsolatedStorageFileStream which is writhing in the wrong encoding, try using the XmlWriter you created this will use utf-8 encoding and Deserialization should work fine

    using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream("class.xml",FileMode.Create,file))
    {
         XmlWriterSettings setting = new XmlWriterSettings();
         setting.Indent = true;
         using (XmlWriter writer = XmlWriter.Create(stream, setting))
         {
             XmlSerializer serializer = new XmlSerializer(typeof(Student));
             serializer.Serialize(writer, new Student() { Name = "AhLim" });
         }
    }
    

    IsolatedStorageFileStream creates header

    <?xml version="1.0"?>
    

    XmlWriter creates header

    <?xml version="1.0" encoding="utf-8"?>