I am trying to use an XML file to store my high score, here is my high score class
[Serializable]
public struct HighScoreData {
public string[] PlayerName;
public int[] Score;
public int[] Level;
public int Count;
public HighScoreData(int count) {
PlayerName = new string[count];
Score = new int[count];
Level = new int[count];
Count = count;
}
}
And here is my XML file :
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
<!-- TODO: replace this Asset with your own XML asset data. -->
<Asset Type="Cellular.HighScoreData">
<PlayerName>
<Item>1</Item>
<Item>2</Item>
<Item>3</Item>
<Item>4</Item>
<Item>5</Item>
<Item>6</Item>
<Item>7</Item>
<Item>8</Item>
<Item>9</Item>
<Item>10</Item>
</PlayerName>
<Score>
<Item>1</Item>开发者_JAVA技巧;
<Item>2</Item>
<Item>3</Item>
<Item>4</Item>
<Item>5</Item>
<Item>6</Item>
<Item>7</Item>
<Item>8</Item>
<Item>9</Item>
<Item>10</Item>
</Score>
<Level>
<Item>1</Item>
<Item>2</Item>
<Item>3</Item>
<Item>4</Item>
<Item>5</Item>
<Item>6</Item>
<Item>7</Item>
<Item>8</Item>
<Item>9</Item>
<Item>10</Item>
</Level>
<Count>10</Count>
</Asset>
Here is my method to Load the data from XML
public void LoadStoredHighScore() {
FileStream stream = File.Open(HighScoreFile, FileMode.Open, FileAccess.Read);
try {
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
highScoreList = (HighScoreData) serializer.Deserialize(stream);
} finally {
stream.Close();
}
}
in "highScoreList = (HighScoreData) serializer.Deserialize(stream);" this line, it gives me exception "There is an error in XML document (0, 0)." with inner exception "Root element is missing".
Am I doing anything wrong? Any help is appreciated.
First off, the serializer will look for a root element named as the type you are trying to deserialize, which it cannot find.
Next, you cannot deserialize into this structure since it have no default constructor. The serializer have no way of figuring out what to pass as the count parameter. Read up on this article to get further details.
Here's a suggested root structure:
<?xml version="1.0" encoding="utf-8" ?>
<HighScoreData>
<PlayerName>
...
</HighScoreData>
精彩评论