How to load data from XML to List
I'd need an advice. I'm developing some easy game in silverlight and I'd need to load level definitions from XML to List but I'm not sure what's the best way to do it.
my xml looks like
<Levels>
<Level levelNumber = "1" startingX="2" startingY="2">
<Cells>
<Cell CellType="A" PositionX="0" PositionY="0" />
<Cell CellType="A" PositionX="1" PositionY="0" />
<Cell CellType="A" PositionX="2" PositionY="0" />
<Cell CellType="A" PositionX="3" PositionY="0" />
<Cell CellType="A" PositionX="4" PositionY="0" />
<Cell CellType="A" PositionX="5" PositionY="0" />
<Cell CellType="A" PositionX="0" PositionY="1" />
<Cell CellType="B" PositionX="1" PositionY="1" />
<Cell CellType="B" PositionX="2" PositionY="1" />
<Cell CellType="B" PositionX="3" PositionY="1" />
<Cell CellType="B" PositionX="4" PositionY="1" />
<Cell CellTy开发者_如何学JAVApe="B" PositionX="5" PositionY="1" />
<Cell CellType="A" PositionX="1" PositionY="2" />
<Cell CellType="B" PositionX="2" PositionY="2" />
<Cell CellType="B" PositionX="3" PositionY="2" />
<Cell CellType="B" PositionX="4" PositionY="2" />
<Cell CellType="A" PositionX="5" PositionY="2" />
<Cell CellType="A" PositionX="1" PositionY="3" />
<Cell CellType="B" PositionX="2" PositionY="3" />
<Cell CellType="B" PositionX="3" PositionY="3" />
<Cell CellType="B" PositionX="4" PositionY="3" />
<Cell CellType="A" PositionX="4" PositionY="3" />
</Cells>
</Level>
</Levels>
and i need to load level to list my Level class
public class Level
{
private int levelNumber;
private int startingX;
private int startingY;
public List<Cell> cellList = new List<Cell>();
public int LevelNumber
{
get { return levelNumber; }
set { levelNumber = value; }
}
...
}
Could you please give me an advice how to do that?
I'd just whip up something quick like this here (assuming there are multiple levels in your xml):
XDocument xdoc = XDocument.Load(url); // assuming you're pulling your xml from a service.
if (xdoc != null)
{
var levels =
(from l in xdoc.Descendants("Level")
select new Level
{
levelNumber = l.Attribute("levelNumber").Value,
startingX = l.Attribute("startingX").Value,
startingY = l.Attribute("startingy").Value,
cellsList = (from c in l.Descendants("Cell")
select new Cell
{
CellType = c.Attribute("CellType").Value,
PositionX = c.Attribute("PostionX").Value,
PositionY = c.Attribute("PositionY").Value
}).ToList()
}
).ToList();
}
I'd consider using LinqToXml here.
I'd write up a quick demo, but this question demonstrates the concepts you'll need quite well@
De/Serialize directly To/From XML Linq
Edit: For clarity, if you make sure your Cell class is annotated with those Xml attributes, the deserialize behaviour should work correctly for you.
精彩评论