views:

40

answers:

1

Assume I have the following XML file:

<Movies>
     <Movie ownerName="Ryan">
          <Title>The Lord of the Rings Trilogy</Title>
          <Title>Saving Private Ryan</Title>
          <Title>etc</Title>
     </Movie>
     <Movie ownerName="Rynina">
          <Title>Foo</Title>
          <Title>Bar</Title>
     </Movie>
</Movies>

What I'm after is using Linq to Xml to retrieve classes of type MovieCollection. MovieCollection has two properties, OwnerName (String) and Movies (List(Of String)).

Generally, I'd do something like:

From entry in movies...<Movie>_
Select New MovieCollection With { _
.OwnerName = [email protected], _
.MovieCollection = entry.<Title>.Value}

However in this case this obviously wont work. Is there anyway to fill the MovieCollection list with all the movies that occur for that owner using Linq?

+2  A: 

You should really name the tags Movie MovieCollection and Title Movie.

Parse your XML with:

Dim doc = XDocument.Parse("<xml>")

or

Dim doc = XDocument.Load("path")

and use this:

Dim movieCollections = From movieCol In doc.Root.Elements("Movie")
                       Select New MovieCollection() With
                              {
                                    .OwnerName = movieCol.Attribute("ownerName"),
                                    .Movies = movieCol.Elements("Title")
                                                      .Select(Function(m) m.Value)
                                                      .ToList()
                              }
lasseespeholt
You just beat me (and I was doing it in C# too)
James Curran
C# is just nicer (maybe because I know it ;-) )...
lasseespeholt