views:

68

answers:

3

Hello.

lets say that I've got this XML:

<items> 
  <item name="thumb"> 
    <downloadStream>test1</downloadStream> 
    <downloadStream>test2</downloadStream> 
    <downloadStream>test3</downloadStream> 
  </item> 
  <item name="photo"> 
    <downloadStream>test5</downloadStream> 
    <downloadStream>test6</downloadStream> 
    <downloadStream>test7</downloadStream> 
  </item> 
</items> 

I'm trying to write a LINQ statement which will convert this to the following strings:

{ "thumb test1",
  "thumb test2",
  "thumb test3",
  "photo test5",
  "photo test6",
  "photo test7", }

In other words, it appends the attribute from the parent node to the inner-string of each child node.

Is their a way that I can use one LINQ query to do something like this? I can find a few ways to break it up into multiple steps, but I have a feeling that their is an easier way.

Thanks!

+1  A: 
XDocument.Load(myXML)
    .Descendants("item")
    .SelectMany(d => d.Descendants()
        .Select(ds => d.Attribute("name").Value + " " + ds.Value));
Yuriy Faktorovich
I ended up choosing another answer. However, I like this one a lot because of it's generality: I could use this technique for things other than xml. Thanks!
brad
A: 
var list = x.Descendants("item")
            .SelectMany(item => item.Elements("downloadStream")
                                    .Select(e => (string)item.Attribute("name") 
                                                 + " " 
                                                 + (string)e)).ToList();
Mehrdad Afshari
A: 

Here it is in VB.NET. Same thing would be possible in C#, but I'm more familiar with the VB syntax.

    Dim itemsXml = <items>
                       <item name="thumb">
                           <downloadStream>test1</downloadStream>
                           <downloadStream>test2</downloadStream>
                           <downloadStream>test3</downloadStream>
                       </item>
                       <item name="photo">
                           <downloadStream>test5</downloadStream>
                           <downloadStream>test6</downloadStream>
                           <downloadStream>test7</downloadStream>
                       </item>
                   </items>
    Dim itemQuery = From ds In itemsXml...<downloadStream> _
                    Select ds.Parent.@name & " " & ds.Value
Dennis Palmer
minor syntax errors aside, this is the answer which was cleanest for me.
brad
@brad, thanks, but syntax *errors*?
Dennis Palmer