将cml反序列化为c#中的类时,从XmlTextAttribute获取int值

xml如下:

<Item>
   <Winner>2</Winner>
</Item>

对于我的 class 定义,我有以下内容:

public enum HomeOrAwayTeamType {Home =1,Away =2,Draw =3,NA = 0};

    class Item
    {
        [XmlIgnore]
        public virtual HomeOrAwayTeamType Winner { get; set; }

        [XmlElement(ElementName = "Winner"), XmlText]
        public virtual string WinnerSerializer
        {
            get { return this.Winner.ToString(); }
            set
            {
                //get 'Away' from HomeOrAwayTeamType
                this.Winner = (HomeOrAwayTeamType)2; //ok
                this.Winner = (HomeOrAwayTeamType)Convert.ToInt32("2"); //ok
                this.Winner = (HomeOrAwayTeamType)int.parse("2"); //ok 

                //get 'NA' from HomeOrAwayTeamType
                this.Winner = (HomeOrAwayTeamType)Convert.ToInt32(value); //fail
                this.Winner = (HomeOrAwayTeamType)int.parse(value); //fail
             }
         }    
    }

    string xml = ""; //xml code
    Item model = default(Item);

    using (var reader = XmlReader.Create(new StringReader(xml)))
    {
        var serializer = new XmlSerializer(typeof(Item));
        model = (Item)serializer.Deserialize(reader);
    }

嗨,大家..如何从XmlTextAttribute获取int值?

请帮忙〜

回答(1)

2 years ago

您的xml字符串为空 . 这对我有用:

string xml = "<Item><Winner>2</Winner></Item>"; //xml code

this.Winner 设置为 Away