We have a requirement to parse an XML document.I have parsed the document with LINQ to XML which results the data type to be’ var’.But I want to make it to be a data type which is accepting a specific class type.
XML Test 21 1 5 Test1 22 1 7
LINQ Query:
XDocument msSqlDoc = XDocument.Load(@"D:\XmlOutput\Test.xml"); List lstExceptions = new List(); lstExceptions.Add("Test1"); lstExceptions.Add("Test2"); var lstMSSqlResult = (from c in msSqlDoc.Descendants("Result") where !lstExceptions.Contains(c.Element("NAME").Value) select new { Name = c.Element("NAME").Value, Columns = c.Element("COLUMNS").Value, Count = c.Element("COUNT").Value , Percentage = c.Element("PERCENTAGE").Value, ID = c.Parent.Attribute("ID").Value, ConnectionID = c.Parent.Attribute("ConnectionID").Value }).ToList();
So I want to create a class with some properties where the result should be that specific class type.
That should look some thing like this:
List lstMSSqlResult = from c in msSqlDoc.Descendants("Result")........}).ToList(); My Class: public class Result { public string Name { get; set; } public string Columns { get; set; } public string Count { get; set; } public string ID { get; set; } public string ConnectionID { get; set; } } Modified LINQ query to accept the result to be above class type: List lstMSSqlResult = (from c in msSqlDoc.Descendants("Result") where !lstExceptions.Contains(c.Element("NAME").Value) select new Result { Name = c.Element("NAME").Value, Columns = c.Element("COLUMNS").Value, Count = c.Element("COUNT").Value , Percentage = c.Element("PERCENTAGE").Value ID = c.Parent.Attribute("ID").Value, ConnectionID = c.Parent.Attribute("ConnectionID").Value }).ToList();
We just need to add the class type ‘Result’ before the select list that will get all the properties from the class so that we can assign all the class properties with the results,that will accept the list of class types as a result.
Note:This will work same for the LINQ to SQL also.