Search code examples
c#xmlxml-serializationxmlserializer

C# Xml Serializable enum type


I want to load a XML file with XML serialization. The type now should be an enum type. So the XML looks like this:

<Ressource name="ressource_name"  type= "Integer" >
                ...
</Ressource>

And I wanted to load it into a class like this:

[Serializable]
public enum Res_Type
{
    [XmlEnum(Name = "Integer")]
    Integer,
    [XmlEnum(Name = "Decimal")]
    Decimal,
    [XmlEnum(Name = "Text")]
    Text
}

public class Ressource
{
   [XmlAttribute]
   public string name { set; get; }
   [XmlAttribute]
   public Res_Type type { get; set; }
}

When I search for this topic I only find different ways of solving it, then I need it to. I need to have the XML like shown above, but I have no idea how to load the information in type as an enum.


Update: To test the serialization and the deserialization I am using this code:

Ressource res = new Ressource();
res.name = "ressource_name";
res.type = Res_Type.Integer;

XmlSerializer serializer = new XmlSerializer(res.GetType());
using (StreamWriter writer = new StreamWriter(@"h:\test.xml"))
{
    serializer.Serialize(writer, res);
}
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Ressource));
StringReader stringReader = new StringReader(@"h:\test.xml");
res = (Ressource)xmlSerializer.Deserialize(stringReader);

And I am getting the error: InvalidOperationException


Solution

  • Your problem is that you are using a StringReader rather than a StreamReader:

    StringReader stringReader = new StringReader(@"h:\test.xml");
    

    This means that your code is attempting to deserialize the contents of the string literal @"h:\test.xml" itself rather than the file to which it refers. This of course fails because the string h:\test.xml is not even well-formed XML.

    Instead you should do:

    var fileName = @"h:\test.xml";
    
    // Write the file as before
    
    using (var reader = new StreamReader(fileName))
    {
        res = (Ressource)xmlSerializer.Deserialize(reader);
    }
    

    Working .Net fiddle here.