<?xml version="1.0" standalone="yes"?> <CompanyInfo> <Employee name="Jon" deptId="123"> <Region name="West"> <Area code="96" /> </Region> <Region name="East"> <Area code="88" /> </Region> </Employee> </CompanyInfo> public class Employee { public string EmployeeName { get; set; } public string DeptId { get; set; } public List<string> RegionList {get; set;} } public class Region { public string RegionName { get; set; } public string AreaCode { get; set; } }
I am trying to read this XML data while I tried this:
XDocument xml = XDocument.Load(@"C:\data.xml"); var xElement = xml.Element("CompanyInfo"); if (xElement != null) foreach (var child in xElement.Elements()) { Console.WriteLine(child.Name); foreach (var item in child.Attributes()) { Console.WriteLine(item.Name + ": " + item.Value); } foreach (var childElement in child.Elements()) { Console.WriteLine("--->" + childElement.Name); foreach (var ds in childElement.Attributes()) { Console.WriteLine(ds.Name + ": " + ds.Value); } foreach (var element in childElement.Elements()) { Console.WriteLine("------->" + element.Name); foreach (var ds in element.Attributes()) { Console.WriteLine(ds.Name + ": " + ds.Value); } } } }
This allows me to get each node, its name and attribute value, and therefore I can save this data in the corresponding field in the database, but it seems long, is not flexible, for example, if the XML structure changes all the ones that need to be performed for foreach , itβs also difficult to filter the data in this way, I need to write certain if statements to filter the data (for example, get employees only from the west, etc.)
I was looking for a more flexible way using linq, something like this:
List<Employees> employees = (from employee in xml.Descendants("CompanyInfo") select new employee { EmployeeName = employee.Element("employee").Value, EmployeeDeptId = ?? get data, RegionName = ?? get data, AreaCode = ?? get data,, }).ToList<Employee>();
But I'm not sure how I can get values ββfrom child nodes and apply filtering (to get only certain employees). Is it possible? Any help is appreciated.
thanks
source share