Roger
Roger

Reputation: 361

Deserializing empty XML tags in C# with enumerations

I've tried to achieve the deserialization as explained in this post with no success:

(* I'm using LinqPad to test this, that's why you can see the .Dump() call at the end of my sample)

In this code, I'm getting "Instance validation error: '' is not a valid value for claves_sexo", because it is empty:

void Main()
{
  string xmlString = "<Products><Product><Id>1</Id><Name>My XML product</Name><Sexo></Sexo></Product></Products>";

  XmlSerializer serializer = new XmlSerializer(typeof(List<Product>), new XmlRootAttribute("Products"));

  StringReader stringReader = new StringReader(xmlString);

  List<Product> productList = (List<Product>)serializer.Deserialize(stringReader);

  productList.Dump();

}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }

    public claves_sexo Sexo {get;set;}
}

public enum claves_sexo
{
    HO,
    MU,
    ND
}

I would like the Sexo member of Product, to be assigned the value ND = 2 for the enum when it's not informed.

I've been playing with the XmlIgnore attribute and created another member to import the value for the empty tag as a String, and assign it to Sexo member, but I didn't succeeded.

FINAL Note: this is the version that finally works:

void Main()
{
    string xmlString = "<Products><Product><Id>1</Id><Name>My XML product</Name><Sexo>ND</Sexo></Product></Products>";  
    XmlSerializer serializer = new XmlSerializer(typeof(List<Product>), new XmlRootAttribute("Products"));
    StringReader stringReader = new StringReader(xmlString);
    List<Product> productList = (List<Product>)serializer.Deserialize(stringReader);
    productList.Dump();
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }

    [XmlIgnore]
    public claves_sexo Sexo {get;set;}

    [XmlElement("Sexo")]
    public string SexoAsString
    {
        get
        {
            return Sexo.ToString();
        }
        set
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                Sexo = claves_sexo.ND;
            }
            else
            {
                Sexo = (claves_sexo)Enum.Parse(typeof(claves_sexo), value);
            }
        }
    }
}

public enum claves_sexo
{
    HO,
    MU,
    ND
}

Thanks to everyone !

Roger

Upvotes: 0

Views: 574

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14477

You can use the XmlEnum attribute:

public enum claves_sexo
{
    [XmlEnum("HO")]HO,
    [XmlEnum("MU")]MU,
    [XmlEnum("")]ND
}

EDIT: You can use multiple names with the same value to handle both "" and "ND":

public enum claves_sexo
{
    [XmlEnum("HO")]HO,
    [XmlEnum("MU")]MU,
    [XmlEnum("ND")]ND,
    [XmlEnum("")]Default = ND,
}

Upvotes: 1

Related Questions