簡體   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