Alex Rivera | Logout

Case insensitive Deserialization

Asked 2010-10-20T06:46:42.840
13

I have an XML file where

We have defined classes to serialize or deserialize XML.

When we deserialize, if the XML contains like below where "type" attribute is in upper case, its throwing error like there is an error in xml(2,2) like that.

<document text="BlankPDF" name="BlankPDF" type="PDF" path="" />

...

[DescriptionAttribute("The sharepoint's document type.")]
[XmlAttribute("type")]
public DocumentType Type
{
    get;
    set;
}

public enum DocumentType
{
    pdf,
    ppt,
    pptx,
    doc,
    docx,
    xlsx,
    xls,
    txt,
    jpg,
    bmp,
    jpeg,
    tiff,
    icon
}

this is how we have defined the attribute.

Is it possible to ignore case while deserializing XML?

c#
Edit
Report

2 Answers

8

Define the values of the DocumentType enumeration in the uppercase or use the standard adaptor property trick:

[Description  ("The sharepoint's document type.")]
[XmlIgnore]
public DocumentType Type { get; set; }

[Browsable    (false)]
[XmlAttribute ("type")]
public string TypeXml
{
    get { return Type.ToString ().ToUpperInvariant () ; }
    set { Type = (DocumentType) Enum.Parse (typeof (DocumentType), value, true) ; }
}
answered 2011-03-05T19:26:09.267
6

For attribute you can also evaluate simply "faking the enum"

public enum RelativeType
    {        
        Mum,
        Dad,
        Son,
        GrandDad,
// ReSharper disable InconsistentNaming
        MUM = Mum,
        DAD = Dad,
        SON = Son,
        GRANDDAD = GrandDad
// ReSharper restore InconsistentNaming
    }

This works in XML Serialization and Deserialization. Serialization uses the main definitions, while deserialization can work with both. It has some side effect, especially when or if you enumerate through Enum.Values or similar. But if you know what you are doing it's effective

answered 2011-07-12T10:34:34.663

Your Answer