Read XML using LINQ to XML C# with Example



Read XML using LINQ to XML C# with Example

 
 
 
1 
Sam 
Male 
423-555-0124 
424-555-0545 
7A Cox Street Acampo CA 95220 USA
2 Lucy Female 143-555-0763 434-555-0567
Jess Bay Alta CA 95701 USA
To read that XML file using LINQ XDocument xdocument = XDocument.Load("Employees.xml"); IEnumerable employees = xdocument.Root.Elements(); foreach (var employee in employees) { Console.WriteLine(employee); } To access single element XElement xelement = XElement.Load("Employees.xml"); IEnumerable employees = xelement.Root.Elements(); Console.WriteLine("List of all Employee Names :"); foreach (var employee in employees) { Console.WriteLine(employee.Element("Name").Value); } To access multiple elements XElement xelement = XElement.Load("Employees.xml"); IEnumerable employees = xelement.Root.Elements(); Console.WriteLine("List of all Employee Names along with their ID:"); foreach (var employee in employees) { Console.WriteLine("{0} has Employee ID {1}", employee.Element("Name").Value, employee.Element("EmpId").Value); } To access all Elements having a specific attribute XElement xelement = XElement.Load("Employees.xml"); var name = from nm in xelement.Root.Elements("Employee") where (string)nm.Element("Sex") == "Female" select nm; Console.WriteLine("Details of Female Employees:"); foreach (XElement xEle in name) Console.WriteLine(xEle); To access specific element having a specific attribute XElement xelement = XElement.Load("..\\..\\Employees.xml"); var homePhone = from phoneno in xelement.Root.Elements("Employee") where (string)phoneno.Element("Phone").Attribute("Type") == "Home" select phoneno; Console.WriteLine("List HomePhone Nos."); foreach (XElement xEle in homePhone) { Console.WriteLine(xEle.Element("Phone").Value); }

0 Comment's

Comment Form

Submit Comment