Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js
Home  • Programming • C#.NET

Example of LINQ to XML in C#

Here is the xml file saved in d:/employees.xml
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Employees>
  3. <Employee>
  4. <ID>111</ID>
  5. <FirstName>Michael</FirstName>
  6. <Department>IT Department</Department>
  7. <City>Pittsburgh</City>
  8. </Employee>
  9. <Employee>
  10. <ID>112</ID>
  11. <FirstName>Hank</FirstName>
  12. <Department>IT Department</Department>
  13. <City>Redmond</City>
  14. </Employee>
  15. <Employee>
  16. <ID>113</ID>
  17. <FirstName>Benjamin</FirstName>
  18. <Department>Human Resources</Department>
  19. <City>Chicago</City>
  20. </Employee>
  21. <Employee>
  22. <ID>114</ID>
  23. <FirstName>Gail</FirstName>
  24. <Department>Marketing</Department>
  25. <City>Ann Arbor</City>
  26. </Employee>
  27. </Employees>
Here is the C# ConsoleApplication code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml.Linq;
  6.  
  7. namespace LINQ_to_XML
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13.  
  14. XElement empXml = XElement.Load(@"d:employees.xml");
  15.  
  16. IEnumerable<XElement> empQuery = from emp in empXml.Descendants("Employee")
  17. where emp.Element("FirstName").Value.Length > 5
  18. select emp;
  19.  
  20.  
  21. foreach (var emp in empQuery)
  22. {
  23.  
  24. Console.WriteLine(emp.Element("Department").Value);
  25.  
  26. }
  27.  
  28. Console.ReadKey();
  29. }
  30.  
  31. }
  32. }
REF: WPSI Schedule class-230, ASP.NET, APCL-Round-17, IDB-BISEW

Comments 0


Copyright © 2025. Powered by Intellect Software Ltd