不区分大小写反序列化

时间:2010-10-20 06:46:43

标签: c#

我有一个XML文件

我们已定义了用于序列化或反序列化XML的类。

当我们反序列化时,如果XML包含如下所示,其中“ type ”属性为大写,则抛出错误就像xml(2,2)中的错误一样。

<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
}

这就是我们定义属性的方式。

在反序列化XML时是否可以忽略大小写?

3 个答案:

答案 0 :(得分:7)

以大写形式定义DocumentType枚举的值或使用标准适配器属性技巧:

[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) ; }
}

答案 1 :(得分:7)

对于属性,您还可以简单地评估“伪造枚举”

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

这适用于XML序列化和反序列化。 序列化使用主要定义,而反序列化可以使用两者。 它有一些副作用,特别是当您或通过Enum.Values或类似枚举时。 但如果你知道你在做什么就有效

答案 2 :(得分:2)

我认为简短的答案是否定的,你不能忽视XmlAttributes中的大小写,因为它们区分大小写(请参阅此article)。这意味着如果您有大量混合大小写的文档,您将遇到许多问题(其中一个问题)。

如果所有文档中的属性名称​​ Type 以大写形式存储,您不仅可以更改XmlAttribute以反映它的存储方式,因此请将该行更改为:

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

或者那不起作用?如果没有,在当前情况下我不确定是否有解决方案。