不区分大小写反序列化

Mah*_*abu 12 c#

我有一个XML文件

我们已经定义了类来序列化或反序列化XML.

当我们反序列化时,如果XML包含如下所示" type "属性是大写的,那么它的抛出错误就像xml(2,2)中的错误一样.

<document text="BlankPDF" name="BlankPDF" type="PDF" path="" />
Run Code Online (Sandbox Code Playgroud)

...

[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
}
Run Code Online (Sandbox Code Playgroud)

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

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

Ant*_*hyy 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) ; }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

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

public enum RelativeType
    {        
        Mum,
        Dad,
        Son,
        GrandDad,
// ReSharper disable InconsistentNaming
        MUM = Mum,
        DAD = Dad,
        SON = Son,
        GRANDDAD = GrandDad
// ReSharper restore InconsistentNaming
    }
Run Code Online (Sandbox Code Playgroud)

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

  • 这不仅适用于属性值(即`type ="GRANDDAD"`)吗?它也适用于属性名称(即`tYpE ="GrandDad"`)?完整的例子是什么样的? (3认同)

Pau*_*eld 2

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

如果所有文档中的属性名称类型都以大写形式存储,您不能只更改 XmlAttribute 以反映它的存储方式,因此将该行更改为:

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

或者那行不通?如果没有,在目前的情况下我不确定是否有解决方案。

  • 我讨厌人们投反对票,并且不发表评论,这样我就可以修复它=P (5认同)