Case insensitive Deserialization

后端 未结 3 495
终归单人心
终归单人心 2021-01-17 11:03

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<

相关标签:
3条回答
  • 2021-01-17 11:24

    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) ; }
    }
    
    0 讨论(0)
  • 2021-01-17 11:29

    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

    0 讨论(0)
  • 2021-01-17 11:44

    I think the short answer is no, you can't ignore case in XmlAttributes as they are case sensitive (see this article). This means you will run into many problems (of which this is one) if you have documents coming in with mixed case.

    If the attribute name Type in all the docs are being stored in upper case can you not just change the XmlAttribute to reflect how it is being stored, so change the line to:

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

    Or would that not work? If not, in the current scenario I'm not sure that there is a solution.

    0 讨论(0)
提交回复
热议问题