Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a LINQ query to get XElement values when XElements have same name

Tags:

c#

linq-to-xml

I have a piece of xml like the following:

<Table>
  <Record>
    <Field>Value1_1</Field>
    <Field>Value1_2</Field>
  </Record>
  <Record>
    <Field>Value2_1</Field>
    <Field>Value2_2</Field>
  </Record>
</Table>

What i would like is a LINQ query that generates an IEnumerable that i can assign as the datasource of a DataGrid. What i have so far is as follows:

var temp = from record in table.Elements("Record")
            select record.Element("Field").Value

The fact that I can have multiple field elements is my stumbling block.

In the above example, what i need is something like an IEnumerable<string,string>. The datagrid would look something like this:

Value1_1, Value1_2
Value2_1, Value2_2
like image 955
JohnC Avatar asked May 20 '09 21:05

JohnC


2 Answers

It sounds like you want to denormalize the field so that it fits in 1 column in your data grid.

Does the following help?

var table = XElement.Parse(@"<Table>
                                <Record><Field>Value1_1</Field><Field>Value1_2</Field></Record>
                                <Record><Field>Value2_1</Field><Field>Value2_2</Field></Record>
                             </Table>");


var temp = from record in table.Elements("Record")
           from field in record.Elements("Field")
           group field.Value by record into groupedFields
           select groupedFields.Aggregate((l, r) => l + ", " + r);

foreach (var row in temp)
    Console.WriteLine(row);

Console.ReadKey();

Disclaimer: I don't do much SQL or LINQ anymore, so this probably could be made better. Feel free to change it.

like image 111
dss539 Avatar answered Sep 24 '22 19:09

dss539


Would something like this help?

var a = from record in table.Elements("Record")
    select new
    {
        one = (string)record.Elements().ElementAt(0),
        two = (string)record.Elements().ElementAt(1)
    };
like image 41
Richard Morgan Avatar answered Sep 25 '22 19:09

Richard Morgan