Linq to XML query
I'm loading from a xml some information about city's points of interest, and my xml structure looks like this:
<InterestPoint>
<id>2</id>
<name>Residencia PAC</name>
<images>
<image>C:\Pictures\Alien Places in The World\20090625-alien11.jpg</image>
<image>C:\Alien Places in The World\20090625-alien13.jpg</image>
</images>
<desc>blah blah blah blah</desc>
<Latitude>40.286458</Latitude>
<Longitude>-7.511921</Longitude>
</InterestPoint>
I'm having trouble to retrieve the images information, I'm only able to get one image, but in these example there are two. The Linq query that i am using is:
CityPins = (from c in PointofInterest.Descendants("InterestPoint")
select new InterestPoint
{
// = c.Attribute("Latitude").Value,
//longitude = c.Attribute("Longitude").Value,
Name = c.Element("nome").Value,
LatLong = new VELatLong(double.Parse(c.Element("Latitude开发者_Python百科").Value), double.Parse(c.Element("Longitude").Value)),
Desc = c.Element("descricao").Value,
Images = (from img in c.Descendants("imagens")
select new POIimage
{
image = new Uri(img.Element("imagem").Value),
}).ToList<POIimage>(),
}).ToList<InterestPoint>();
Images is a List<POIimages>
where POIimage is a class with a Uri field.
Could someone help me fix this query?
By writing c.Descendants("images")
, you are iterating over all of the <images>
elements, and getting their first <image>
element by calling img.Element("imagem")
.
Since there is only one <images>
(which happens to contain multiple <image>
elements), you're only getting one image.
The other <image>
elements inside of <images>
are ignored, since you don't do anything with them.
You need to call c.Descendants("image")
in the inner query to get all of the <image>
elements.
For example:
Images = (from img in c.Descendants("image")
select new POIimage { image = new Uri(img.Value) }
).ToList(),
Try this ( couldn;t test, don't have VS editor as of now).
...
Images = (from img in c.Descendants("image")).SelectMany( new POIimage
{
image = new Uri(img.Element("imagem").Value)
}).ToList<POIimage>(),
精彩评论