How to Deserialize XML using DataContractSerializer

后端 未结 1 1052
北恋
北恋 2020-12-16 14:12

I\'m trying to deserialize an xml document:

               

    
                 


        
1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 14:47

    I figured it out. Maybe there are other implementations but this works. For the life of me I couldn't find any examples that use List inside an object. Here is a working example:

    XML document to parse:

                   
    
        
            TEST1
            TESTGAME1
            1111111
            
                5,00
            
        
        
            TEST2
            TESTGAME2
            222222
            
                0,30
                0,90
            
        
    
    

    .cs class:

    namespace XmlParse
    {
        using System;
        using System.Collections.Generic;
        using System.Globalization;
        using System.Runtime.Serialization;
    
        [DataContract(Name = "game", Namespace = "")]
        public class Game
        {
            [DataMember(Name = "name", Order = 0)]
            public string Name { get; private set; }
    
            [DataMember(Name = "code", Order = 1)]
            public string Code { get; private set; }
    
            [DataMember(Name = "ugn", Order = 2)]
            public string Ugn { get; private set; }
    
            [DataMember(Name = "bets", Order = 3)]
            public Bets Bets { get; private set; }
        }
    
        [CollectionDataContract(Name = "bets", ItemName = "bet", Namespace = "")]
        public class Bets : List
        {
            public List BetList
            {
                get
                {
                    return ConvertAll(y => decimal.Parse(y, NumberStyles.Currency));
                }
            }
        }
    
        [CollectionDataContract(Name = "games", Namespace = "")]
        public class Games : List
        {
        }
    }
    

    Read and parse xml document:

    string fileName = Path.Combine(this.path, "Document.xml");
    DataContractSerializer dcs = new DataContractSerializer(typeof(Games));
    FileStream fs = new FileStream(fileName, FileMode.Open);
    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
    
    Games games = (Games)dcs.ReadObject(reader);
    reader.Close();
    fs.Close();
    

    0 讨论(0)
提交回复
热议问题