3

Let's say I want to parse following XML file:

 <EmployeeDetails>
     <Employee>        //List of Employees
      <Id>11</Id>
      <name>a</name>
      <Dependents>    //List of Dependents of a single employee
        <Dependent>
          <name>a1</name>
          <age>50</age>      
        </Dependent>
        <Dependent>
          <name>a2</name>
          <age>52</age>      
        </Dependent>
      </Dependents>
      <Department>           //Unique per Emp
        <DeptId>1</DeptId>
        <DeptName>D1</DeptName>   
      </Department>
    </Employee>
    <Employee>
     -----
    --------
    </Employee>
   </EmployeeDetails>

Following is the Class Structure for above file:

public class Employee
{
  public int id {get; set;}
  public string name {get; set;}
  public List<Dependents> Dependents {get; set;}
  public Department Department {get; set;}
}

public class Dependents
{
  public string name {get; set;}
  public int age {get; set;}
}

public class Department
{
  public int DeptId {get; set;}
  public string DeptName {get; set;}
}

Now, I want to parse above XML structure and I am able to do it for id and name of Employee but I am unable to parse further.

Let me show you what I've done so far :

public static void ParseXml() 
{
  string xmldoc = //let's assume I've data in this string

            XDocument xdoc = new XDocument();
            xdoc = XDocument.Parse(xmldoc);

            var query = from d in xdoc.Root.Descendants("Employee")
                        select d;

            List<Employee> lsEmp = new List<Employee>();

            foreach (var q in query)
            {
                Employee obj = new Employee();
                obj.Id = Convert.ToInt32(q.Element("Id").Value);
                obj.name = q.Element("name").Value;


                obj.Department = new Department();
                obj.Dependents = new List<Dependents>();

                 // how to get data further?



               lsEmp.Add(obj);
           }

So I need help in order to parse XML data from these list of Dependents and Department object.

3
  • If you wrote this code, and if I understand your question, you already know how to drill into nodes : q.Element("Id") & q.Element("name"), so what is the problem? Commented Mar 29, 2018 at 12:10
  • Have you considered using an XmlSerializer? If the classes are defined right it will just read it in one go. Commented Mar 29, 2018 at 12:23
  • 1
    @AndrewTruckle I know it's easy to do with XMLSerializer but i won't to achieve this with LINQ-TO-XML Commented Mar 29, 2018 at 12:34

3 Answers 3

3

Following your own structure, here's the way to continue parsing the data you need.

// how to get data further?
var allDependents = q.Elements("Dependents").Elements("Dependent");

foreach (var b in allDependents)
{
    Dependents d = new Dependents
    {
        age = Convert.ToInt32(b.Element("age").Value),
        name = b.Element("name").Value
    };
    obj.Dependents.Add(d);
}

obj.Department.DeptId = Convert.ToInt32(q.Element("Department").Element("DeptId").Value);
obj.Department.DeptName = q.Element("Department").Element("DeptName").Value;

Notice that I have used .Elements("") to get all the child nodes under Dependents

Sign up to request clarification or add additional context in comments.

Comments

3

Here is code using just linq and no for loops

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string xml = File.ReadAllText(FILENAME);
            ParseXml(xml);

        }
        public static void ParseXml(string xml)
        {

            XDocument xdoc = XDocument.Parse(xml);

            List<Employee> employees = xdoc.Descendants("Employee").Select(x => new Employee () {
                id = (int)x.Element("Id"),
                name = (string)x.Element("Name"),
                Department = x.Elements("Department").Select(y => new Department() { DeptId = (int)y.Element("DeptId"), DeptName = (string)y.Element("DeptName")}).FirstOrDefault(),
                Dependents = x.Descendants("Dependent").Select(y => new Dependents() { age = (int)y.Element("age"),  name = (string)y.Element("name")}).ToList()
            }).ToList();
        }


    }
    public class Employee
    {
        public int id { get; set; }
        public string name { get; set; }
        public List<Dependents> Dependents { get; set; }
        public Department Department { get; set; }
    }

    public class Dependents
    {
        public string name { get; set; }
        public int age { get; set; }
    }

    public class Department
    {
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    }

}

1 Comment

Thank you for providing a different approach. +1.
1

Maybe this can help you:

XDocument xdoc = new XDocument();
        xdoc = XDocument.Parse(xmldoc);

        var query = from d in xdoc.Root.Descendants("Employee")
                    select d;

        List<Employee> lsEmp = new List<Employee>();

        foreach (var q in query)
        {
            Employee obj = new Employee();
            obj.Id = Convert.ToInt32(q.Element("Id").Value);
            obj.name = q.Element("name").Value;


            obj.Department = new Department()
            {
                DeptName = q.Element("Department").Element("name").Value,
                DeptId = 
               Convert.ToInt32(q.Element("Department").Element("age").Value)
            };
            obj.Dependents = new List<Dependents>();


            foreach (var e in q.Element("Dependents").Elements("Dependent"))
            {
                var dependent = new Dependents()
                {
                    name = e.Element("name").Value,
                    age = Convert.ToInt32(e.Element("age").Value)
                };
                obj.Dependents.Add(dependent);
            }

            lsEmp.Add(obj);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.