VB.NET: Populating a list in Linq
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开发者_如何学JAVA>
<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 = entry.@Title.Value, _
.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?
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()
}
Try to use the serialization
http://support.microsoft.com/kb/316730
精彩评论