Solved

Query XML using Linq

Posted on 2012-03-23
10
1,404 Views
Last Modified: 2012-03-23
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
Comment
Question by:sansoftura
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
10 Comments
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37758856
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
 
LVL 18

Expert Comment

by:Gary Davis
ID: 37758883
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
 
LVL 6

Author Comment

by:sansoftura
ID: 37758928
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
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37758955
using System.Linq;
using System.Xml.Linq;

Also add reference to System.Xml and System.Xml.Linq from add references in VS
0
 
LVL 6

Author Comment

by:sansoftura
ID: 37759031
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
 
LVL 18

Expert Comment

by:Gary Davis
ID: 37759098
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
 
LVL 6

Author Comment

by:sansoftura
ID: 37759115
OK here it is
<EmployeeList xmlns="http://...">
<id>1</id>
    <name>abc</name>
  </EmployeeList>
0
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 200 total points
ID: 37759149
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
 
LVL 18

Accepted Solution

by:
Gary Davis earned 300 total points
ID: 37759236
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
 
LVL 18

Expert Comment

by:Gary Davis
ID: 37759302
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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…

627 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question