Solved

Query XML using Linq

Posted on 2012-03-23
10
1,355 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
  • 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
 
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
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 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…
This video discusses moving either the default database or any database to a new volume.

758 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now