So i've created a xml with several levels inside a "root" element. Basicly this is how it looks:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Collectibles>
<SaveAltars>
<SaveAltar>
<Location>
<row>0</row>
<col>1</col>
</Location>
<Quantity>1</Quantity>
<Collected />
</SaveAltar>
<SaveAltar>
<Location>
<row>0</row>
<col>3</col>
</Location>
<Quantity>1</Quantity>
<Collected />
</SaveAltar>
<Fruits>
<Fruit>
<Location>
<row>0</row>
<col>1</col>
</Location>
<Quantity>7</Quantity>
<Collected />
</Fruit>
<Fruit>
<Location>
<row>0</row>
<col>4</col>
</Location>
<Quantity>4</Quantity>
<Collected />
</Fruit>
</Fruits>
<Lizards>
<Lizard>
<Location>
<row>0</row>
<col>1</col>
</Location>
<Quantity>1</Quantity>
<Collected />
</Lizard>
<Lizard>
<Location>
<row>0</row>
<col>3</col>
</Location>
<Quantity>1</Quantity>
<Collected />
</Lizards>
</Collectibles>
And i also have simples classes like this:
class Fruit
{
public string Col;
public string Row;
public string Quantity;
public string Collected;
}
And i'm willing to make a list of Fruits/Lizard/SaveAltars using linQ To Xml But i don't know how do you have to proceed to read every level of the collectibles list. Like reading one Fruit then save it into a classe and put it in a list.
How can i achieve this please?
Right now i tried something like
XDocument collectXml = XDocument.Load("collect.xml");
foreach (XElement elem in collectXml.Descendants("Collectibles").Descendants("SaveAltars"))
{
MessageBox.Show(elem.Descendants("Location").Descendants("row").ToString());
}
But it shows some random code, i don't know how to populate a classe and save it in a list for every element in the xml file :/
Can u please help?
It sounds like you want something like:
var fruit = collectXml
.Descendants("Fruit")
.Select(x => new Fruit {
Col = (string) x.Element("Location").Element("Col"),
Row = (string) x.Element("Location").Element("Row"),
Quantity = (string) x.Element("Quantity"),
Collected = x.Element("Collected") == null ? "Yes" : "No"
})
.ToList();
As noted in a comment though, you should really consider using more appropriate types - you possibly want a Location
type for the location (with int
values for Row
and Column
), an int
for Quantity
, and probably bool
for Collected
. Oh, and I'd strongly recommend using properties rather than public fields.
See more on this question at Stackoverflow