Example of LINQ to XML in C#
Here is the xml file saved in d:/employees.xml
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<ID>111</ID>
<FirstName>Michael</FirstName>
<Department>IT Department</Department>
<City>Pittsburgh</City>
</Employee>
<Employee>
<ID>112</ID>
<FirstName>Hank</FirstName>
<Department>IT Department</Department>
<City>Redmond</City>
</Employee>
<Employee>
<ID>113</ID>
<FirstName>Benjamin</FirstName>
<Department>Human Resources</Department>
<City>Chicago</City>
</Employee>
<Employee>
<ID>114</ID>
<FirstName>Gail</FirstName>
<Department>Marketing</Department>
<City>Ann Arbor</City>
</Employee>
</Employees>
Here is the C# ConsoleApplication code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace LINQ_to_XML
{
class Program
{
static void Main(string[] args)
{
XElement empXml = XElement.Load(@"d:employees.xml");
IEnumerable<XElement> empQuery = from emp in empXml.Descendants("Employee")
where emp.Element("FirstName").Value.Length > 5
select emp;
foreach (var emp in empQuery)
{
Console.WriteLine(emp.Element("Department").Value);
}
Console.ReadKey();
}
}
}
REF: WPSI Schedule class-230, ASP.NET, APCL-Round-17, IDB-BISEW
Comments 0