Search code examples
c#xmlvisual-studio-2012deserializationxml-serialization

Deserialisation of xml file not working when I do it the usual way in visual studio


I am trying to deserialize a xml file. I have done this in the past and it always worked like a charm, but not this time. if someone sees my mistake and can help, that would be very much appreciated! The last time I was working with it in unity, this time it is a visual studio console application.

Edit: I probably need to set the "xmlns" attribute somehow, when working in visual studio, but to what?

I get this error message:

 Error in XML-Document (2,2)
<Information xmlns=''> not exspected

My files look like this:

Information.xml:

<?xml version="1.0" encoding="utf-8"?>
<InformationenContainer>
  <Informations>
    <Information ID="foo"/>
  </Informations>
</InformationenContainer>

Program.cs:

class Program
{
    static void Main(string[] args)
    {
        string filename = "C:\\Users\\Ruben Bohnet\\Documents\\Visual Studio 2015\\Projects\\Tool\\Tool\\Informationen.xml";
        InformationenContainer IC = InformationenContainer.Load(filename);
    }
}

InformationController.cs:

using System.IO;
using System.Xml.Serialization;


[XmlRoot("InformationenContainer")]
public class InformationenContainer
{
    [XmlArray("Informations"), XmlArrayItem("Information",typeof(Information))]
    public Information[] Informations;

    public static InformationenContainer Load(string path)
    {
        var serializer = new XmlSerializer(typeof(InformationenContainer));
        using (var stream = new FileStream(path, FileMode.Open))
        {
            InformationenContainer ic = serializer.Deserialize(stream) as InformationenContainer;
            return ic;
        }
    }

}

Information.cs:

using System;
using System.Xml.Serialization;

public class Information
{
    //Attribuites to serialize
    [XmlAttribute("ID")]
    public String ID;
}

Solution

  • Found the solution myself by just creating an InformationContainer and serializing it, the resulting xml file looked like this:

    <?xml version="1.0"?>
    <InformationenContainer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Informations>
        <Information ID="foo" />
      </Informations>
    </InformationenContainer>