将cml反序列化为c#

时间:2016-06-23 02:37:03

标签: c# serialization

xml如下:

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

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


    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 个答案:

答案 0 :(得分:0)

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

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

this.Winner设置为Away