Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Query XML using Linq

Posted on 2012-03-23
10
Medium Priority
?
1,413 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
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!

 
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 800 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 1200 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

Implementing Azure Infrastructure Exam 70-533

This course is designed to familiarize and instruct students in the content that is covered by Microsoft Exam 70-533, Implementing Microsoft Azure Solutions. It focuses on all the November 2016 objective domain topics.

Question has a verified solution.

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

A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
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…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

660 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