I have a problem. In my Xamarin Forms app I do a webcall to my webpage, where I collect XML to use in the app. I parse the XML to 3 different Lists.
- Albums
- Images
- Formats
Now here is what my xml looks like:
<Data>
<Albums>
<Album>
<Image></Image>
<Image></Image>
<Image></Image>
</Album>
<Album>
<Image></Image>
<Image></Image>
</Album>
</Albums>
<Images>
<Image></Image>
<Image></Image>
<Image></Image>
<Image></Image>
</Images>
<Formats>
<Format></Format>
<Format></Format>
</Formats>
</Data>
After parsing it, the wanted result is:
lstAlbums.Count = 2
lstImages.Count = 4
lstFormats.Count = 2
But apparently it counts all the <> tags in the full xml, so lstImages has a count of 9, because 5 from the albums and 4 from the <Images>
Here is my c# code:
if (!string.IsNullOrEmpty(xmlString))
{
doc = XDocument.Parse(xmlString);
}
//Check if xml has any elements
if (!string.IsNullOrEmpty(xmlString) && doc.Root.Elements().Any())
{
App.lstAlbums = doc.Descendants("Albums").Descendants("Album").Select(d =>
new Album
{
Id = Convert.ToInt32(d.Element("Id").Value),
Name = d.Element("Name").Value,
Images = doc.Descendants("Album").Descendants("Image").Select(a =>
new myImage
{
Id = Convert.ToInt32(a.Element("Id").Value),
Name = a.Element("Name").Value,
Size = a.Element("Size").Value,
Price = Convert.ToDecimal(a.Element("Price").Value)
}).ToList(),
Prijs = Convert.ToDecimal(d.Element("Price").Value)
}).ToList();
App.lstImages = doc.Descendants("Images").Descendants("Image").Select(e =>
new myImage
{
Id = Convert.ToInt32(e.Element("Id").Value),
Name = e.Element("Name").Value
}).ToList();
App.lstFormats = doc.Descendants("Formats").Descendants("Format").Select(e =>
new Format
{
Id = Convert.ToInt32(e.Element("Id").Value),
Size = e.Element("Size").Value,
Price = Convert.ToDecimal(e.Element("Price").Value)
}).ToList();
}
How can I fix this?
Descendentsmethod is recursive; if you only intend to look one level, useElementsinstead, but frankly this looks like a good fit forXmlSerializerinstead of manual parsing.