Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1416
  • Last Modified:

Query XML using Linq

How do I get the employee list from below XML

<?xml version="1.0" encoding="utf-8"?>
<Employee>
  <Some_XML_1 />
  <Some_XML_2 />
  <EmployeeList>
    <id>1</id>
    <name>abc</name>
  </EmployeeList>
  <EmployeeList>
    <id>2</id>
    <name>def</name>
  </EmployeeList>
  <EmployeeList>
    <id>3</id>
    <name>hij</name>
  </EmployeeList>
</Employee>

I need a collection of ID & Name. Is it possible in LINQ or should we go back to DOM
0
sansoftura
Asked:
sansoftura
  • 4
  • 3
  • 3
2 Solutions
 
BuggyCoderCommented:
here is code for linq to xml for the same:-
var strXML =
                "<Employee><EmployeeList><id>1</id><name>abc</name></EmployeeList>" +
                "<EmployeeList><id>2</id><name>def</name></EmployeeList>" +
                "<EmployeeList><id>3</id><name>hij</name></EmployeeList></Employee>";

            var xmlElem = XElement.Parse(strXML);

            var list = xmlElem.Descendants("EmployeeList")
                .Select(e => new
                                 {
                                     ID = e.Descendants("id").First().Value,
                                     Name = e.Descendants("name").First().Value
                                 })
                .ToList();

Open in new window

0
 
Gary DavisDir Internet SvcsCommented:
My version - use LinqPad for easy development:

      XElement data = XElement.Parse(
      @"<Employee>
            <Some_XML_1 />
            <Some_XML_2 />
            <EmployeeList>
                  <id>1</id>
                  <name>abc</name>
            </EmployeeList>
            <EmployeeList>
                  <id>2</id>
                  <name>def</name>
            </EmployeeList>
            <EmployeeList>
                  <id>3</id>
                  <name>hij</name>
            </EmployeeList>
            </Employee>");

      var employees = data.Descendants("EmployeeList");
      
      foreach (var employee in employees)
      {
            var id = employee.Element("id").Value;
            var name = employee.Element("name").Value;
            // Rest of code...
      }

Gary Davis
0
 
sansofturaAuthor Commented:
Thanks, But I get the following error for the the below code:

XElement xmlElem = XElement.Parse(strXML);

            var list = xmlElem.Descendants("EmployeeList")
                .Select(e => new
                                 {
                                     ID = e.Descendants("id").First().Value,
                                     Name = e.Descendants("name").First().Value
                                 })
                .ToList();



'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' could be found (are you missing a using directive or an assembly reference?)
0
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
BuggyCoderCommented:
using System.Linq;
using System.Xml.Linq;

Also add reference to System.Xml and System.Xml.Linq from add references in VS
0
 
sansofturaAuthor Commented:
Sorry both the solutions doesnt work. I get the count as 0 for the list  & its not even going inside the foreach loop. But there are records in the XML

Could it be because of xml namespace in the EmployeeList node?
0
 
Gary DavisDir Internet SvcsCommented:
There is no namespace shown in your data example above but if there is one in your actual data, it could have an effect.
0
 
sansofturaAuthor Commented:
OK here it is
<EmployeeList xmlns="http://...">
<id>1</id>
    <name>abc</name>
  </EmployeeList>
0
 
BuggyCoderCommented:
ok here is code for console app that works perfectly for me:-
using System;
using System.Linq;
using System.Xml.Linq;

namespace EE_Console
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var strXML =
                "<Employee><EmployeeList><id>1</id><name>abc</name></EmployeeList>" +
                "<EmployeeList><id>2</id><name>def</name></EmployeeList>" +
                "<EmployeeList><id>3</id><name>hij</name></EmployeeList></Employee>";

            var xmlElem = XElement.Parse(strXML);

            var list = xmlElem.Descendants("EmployeeList")
                .Select(e => new
                                 {
                                     ID = e.Descendants("id").First().Value,
                                     Name = e.Descendants("name").First().Value
                                 })
                .ToList();

            if (list.Count > 0)
            {
                Console.WriteLine("Total Items In List :{0}", list.Count);
                list.ForEach(Console.WriteLine);
            }

            Console.Read();
        }
    }
}

Open in new window

Also i am attaching a screenshot for your reference.
Untitled.jpg
0
 
Gary DavisDir Internet SvcsCommented:
This is my updated solution with namespace support.
Assuming each EmployeeList looks like this:

   <EmployeeList xmlns="http://a.com">

This is the code:

      XNamespace ns = "http://a.com";
      var employees = data.Descendants(ns + "EmployeeList");

      foreach (var employee in employees)
      {
            var id = employee.Element(ns + "id").Value;
            var name = employee.Element(ns + "name").Value;
            // Rest of code...
      }

Gary
0
 
Gary DavisDir Internet SvcsCommented:
A little better performance within the loop:

      XNamespace ns = "http://a.com";
      XName Id = ns + "id";
      XName Name = ns + "name";      

      var employees = data.Descendants(ns + "EmployeeList");
      employees.Dump("Employees");

      foreach (var employee in employees)
      {
            var id = employee.Element(Id).Value;
            var name = employee.Element(Name).Value;
            // Rest of code...
      }

Details at http://msdn.microsoft.com/en-us/library/cc716786.aspx

BuggyCoder's solution will also work with the appropriate edits.

Gary
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now