繁体   English   中英

使用c#中的Value属性从Xml反序列化枚举

[英]Deserialize Enum from Xml using Value property in c#

我正在尝试用C#编写ONIX for book导入工具。 我开始使用Xsd2Code创建类,并获得了一个包含所有属性的大文件,经过一些调整后,在反序列化时不会产生任何错误。

我试图一次性将整个元素反序列化为内存中的一个大对象,然后用它做一些事情(比如将它保存到数据库中)。

除了有很多属性之外,Xsd2Code生成类的方式有点奇怪,至少对我而言。

这是应该是Product对象的属性的类之一:

public partial class NotificationType
{
    public NotificationTypeRefname refname { get; set; }
    public NotificationTypeShortname shortname { get; set; }

    public SourceTypeCode sourcetype { get; set; }

    public List1 Value { get; set; }
}

我想请你注意这一行:

    public List1 Value { get; set; }

“List1”是一个枚举,定义如下:

public enum List1
{
    [System.Xml.Serialization.XmlEnum("01")]
    Item01,

    [System.Xml.Serialization.XmlEnum("02")]
    Item02, etc...

我的问题是在反序列化期间,所有字段都正确地反序列化除了枚举。

我尝试使用XmlEnum(“NotificationType”)等来装饰属性......没有!

这是我的反序列化代码:

var p = new Product();
XmlSerializer pserializer = new XmlSerializer(p.GetType());
object pDeserialized = pserializer.Deserialize(reader);
p = (Product) pDeserialized;

这是XML中这个元素的样子:

<NotificationType>03</NotificationType>

Product对象在C#中的属性是:

public NotificationType NotificationType { get; set; }

如果我将其更改为:

public List1 NotificationType { get; set; }

反序列化正确显示'Item03',这意味着它确实读取了XML中的任何内容。 如果我像上面那样离开它,NotificationType类的'Value'属性永远不会被填充,并且始终显示Item01(Enum的默认值)。

我已经用尽所有关于SO和网络搜索的问题,为什么这个Value属性适用于某些类型(字符串)但不适用于枚举。 我错过了什么吗?

很抱歉这个问题和代码很长。 感谢任何人都可以解决这个问题。 现在已经坚持了整整一天。

试试这个:

public partial class NotificationType
{
    public NotificationTypeRefname refname { get; set; }
    public NotificationTypeShortname shortname { get; set; }
    public SourceTypeCode sourcetype { get; set; }

    public List1 Value { get {
        return (List1)Enum.Parse(typeof(List1), 
            Enum.GetName(typeof(List1), int.Parse(List1Value) - 1));
    }}

    [XmlText]
    public string List1Value { get; set; }
}

[UPDATE]

以来:

  1. 我还尝试首先使用XmlText属性装饰成员,但发生了以下异常:

    无法序列化“ConsoleApplication1.NotificationType”类型的对象。 考虑将ConsoleApplication1.List1中的XmlText成员'ConsoleApplication1.NotificationType.Value'的类型更改为字符串或字符串数​​组。

  2. 你想避免我在答案中的初步方法,

真正的解决方案是,除了将XmlText属性应用于Value ,所有其他成员都应该使用XmlIgnoreAttribute进行修饰。 我相信单独使用XmlText不是一个有保证的解决方案,因为结果取决于其他成员的存在。

public class NotificationType
{
    [XmlIgnore] // required
    public NotificationTypeRefname refname { get; set; }
    [XmlIgnore] // required
    public NotificationTypeShortname shortname { get; set; }
    [XmlIgnore] // required
    public SourceTypeCode sourcetype { get; set; }

    [XmlText] // required
    public List1 Value { get; set; }
}

尝试将[System.Xml.Serialization.XmlTextAttribute()]添加到public List1 Value { get; set; } public List1 Value { get; set; } public List1 Value { get; set; }属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM