Wednesday, April 19, 2017

How to quickly parse XML string into a object list with System.XML.linq in C#?

Today i discover that it is much neat and fast to parse an XML String into Object list when I utilized the System.XML.Linq.

here is the code to demostrate this, you can create a console app to see how it works.

class Program
    {
        static void Main(string[] args)
        {
            string xmlString = @"<FCDetail><FCDetail><FC> ZRL - 02 </FC><FCDesc> FC Description </FCDesc>
                <FGC> FAC </FGC><FGroup> Accessories </FGroup></FCDetail></FCDetail><FCDetailMessage></FCDetailMessage>";
            string xml = "<FCRoot>" + xmlString + "</FCRoot>";
            var xDoc = XDocument.Parse(xml);

            var listNode = xDoc.Root.Elements("FCDetail").FirstOrDefault();

            List<FCodeModel> list = new List<FCodeModel>();
            foreach (var fCodeElement in listNode.Elements("FCDetail"))
            {
                list.Add(new FCodeModel
                {
                    FC =fCodeElement.Elements("FC").Select(e => e.Value).FirstOrDefault() ?? "",
                    FCDesc =fCodeElement.Elements("FCDesc").Select(e => e.Value).FirstOrDefault() ?? "",
                    FGC =fCodeElement.Elements("FGC").Select(e => e.Value).FirstOrDefault() ?? "",
                    FGroup =fCodeElement.Elements("FGroup").Select(e => e.Value).FirstOrDefault() ?? ""
                });
            }
           
    }

    public class FCodeModel
    {
        [JsonProperty("fCode")]
        public string FC { get; set; }
        [JsonProperty("fCodeDesc")]
        public string FCDesc { get; set; }
        [JsonProperty("fGroupCode")]
        public string FGC { get; set; }
        [JsonProperty("FGroup")]
        public string FGroup { get; set; }
    }

No comments:

Post a Comment