Search code examples
c#xmlxml-serializationxml-deserialization

C# how to deserialize XML string which has nested same node


<n-hierarchy>
    <n name="ABC" n_id="971" />
    <n name="XYZ" n_id="972">
        <n name="jkl" n_id="973">
            <n name="wer" n_id="974"/>
            <n name="cvb" n_id="975"/>
        </n>
    </n>
</n-hierarchy>

above is the sample XML string which I receive from an API and I want to deserialize into a C# object


Solution

  • Try following :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;
    
    
    namespace ConsoleApp10
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                XElement hier = doc.Descendants("n-hierarchy").FirstOrDefault();
    
                Node root = new Node();
                root.name = "root";
                root.parse(hier);
            }
        }
        public class Node
        {
            public string name { get; set; }
            public string id { get; set; }
            public List<Node> children { get;set;}
            
            public void parse(XElement element)
            {
                foreach (XElement childElement in element.Elements("n"))
                {
                    if (children == null) children = new List<Node>();
                    Node child = new Node();
                    children.Add(child);
                    child.name = (string)childElement.Attribute("name");
                    child.id = (string)childElement.Attribute("n_id");
                    child.parse(childElement);
    
                }
    
    
            }
        }
    
    }