Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive Deserialization

Tags:

c#

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?

like image 864
Mahendra babu Avatar asked Oct 20 '10 06:10

Mahendra babu


2 Answers

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) ; }
}
like image 117
Anton Tykhyy Avatar answered Sep 23 '22 04:09

Anton Tykhyy


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

like image 30
ZeePrime Avatar answered Sep 23 '22 04:09

ZeePrime