DotNetDude
DotNetDude

Reputation: 155

Select Elements To List Linq

Trying to extract list of "Queue" Elements into a new list of Queue objects. I have the following xml:

<MSMQData>
 <Queues>
  <Queue env="LOCAL" server="WORK150">FormatName:DIRECT=OS:WKSTN150\private$\localqueue1</Queue>
  <Queue env="TEST" server="TEST01">FormatName:DIRECT=OS:dev-test01\private$\testqueue</Queue>
  <Queue env="PROD" server="empty"></Queue>
  <Queue env="PROD" server="empty"></Queue>
 </Queues>
</MSMQData>

Here's my code that obviously does not bring me back a list of Queue Elements that I'm trying to retrieve. What am I missing here?

var queues = (from col in xmlMSMQLoad.Descendants("Queues")
              select col)
             .Select(c => new Queue
             {
                 Environment = c.Element("Queue").Attribute("env").Value,
                 Server = c.Element("Queue").Attribute("server").Value,
                 QueueName = c.Element("Queue").Value
             })
             .ToList();

By the way I do have a class called Queue with these properties in it.

Upvotes: 1

Views: 5027

Answers (3)

mccow002
mccow002

Reputation: 6914

var queues = doc
        .Descendants("Queue")
        .Select(x => new Queue
            {
                Env = x.Attribute("env").Value,
                Server = x.Attribute("server").Value,
                QueueName = x.Value
            })
        .ToList();

You're linq was a little messed up. By selecting the "Queue" descendants, your iterating over them rather than always selecting the first "Queue" node in your select. I've never liked the long form of linq, and have never had any luck combining the chained and long forms. Hope this helps!

Upvotes: 1

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

Your current approach finds "Queues" then only selects the first "Queue" item. It doesn't grab all of them. What you want to do is use Descendants("Queue") or first select the "Queues" element and then its "Queue" elements.

Use this query instead:

var queues = (from c in xml.Element("Queues").Elements("Queue")
             select new Queue
             {
                 Environment = c.Attribute("env").Value,
                 Server = c.Attribute("server").Value,
                 QueueName = c.Value
             }).ToList();

Upvotes: 7

escargot agile
escargot agile

Reputation: 22379

In c.Element("Queue"):

c is the "Queues" element, and c.Element("Queue") is the first "Queue" element. Therefore you only get the first one.

Upvotes: 1

Related Questions