XNA: Best way to load and read a XML file?
Posted
by Rosarch
on Stack Overflow
See other posts from Stack Overflow
or by Rosarch
Published on 2010-03-13T19:09:08Z
Indexed on
2010/03/13
20:05 UTC
Read the original article
Hit count: 330
I'm having difficulty doing this seemingly simple task. I want to load XML files with the same ease of loading art assets:
content = new ContentManager(Services);
content.RootDirectory = "Content";
Texture2d background = content.Load<Texture2D>("images\\ice");
I'm not sure how to do this. This tutorial seems helpful, but how do I get a StorageDevice
instance?
I do have something working now, but it feels pretty hacky:
public IDictionary<string, string> Get(string typeName)
{
IDictionary<String, String> result = new Dictionary<String, String>();
xmlReader.Read(); // get past the XML declaration
string element = null;
string text = null;
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
element = xmlReader.Name;
break;
case XmlNodeType.Text:
text = xmlReader.Value;
break;
}
if (text != null && element != null)
{
result[element] = text;
text = null;
element = null;
}
}
return result;
}
I apply this to the following XML file:
<?xml version="1.0" encoding="utf-8" ?>
<zombies>
<zombie>
<health>100</health>
<positionX>23</positionX>
<positionY>12</positionY>
<speed>2</speed>
</zombie>
</zombies>
And it is able to pass this unit test:
internal virtual IPersistentState CreateIPersistentState(string fullpath)
{
IPersistentState target = new ReadWriteXML(File.Open(fullpath, FileMode.Open));
return target;
}
/// <summary>
///A test for Get with one zombie.
///</summary>
//[TestMethod()]
public void SimpleGetTest()
{
string fullPath = "C:\\pathTo\\Data\\SavedZombies.xml";
IPersistentState target = CreateIPersistentState(fullPath);
string typeName = "zombie";
IDictionary<string, string> expected = new Dictionary<string, string>();
expected["health"] = "100";
expected["positionX"] = "23";
expected["positionY"] = "12";
expected["speed"] = "2";
IDictionary<string, string> actual = target.Get(typeName);
foreach (KeyValuePair<string, string> entry in expected)
{
Assert.AreEqual(entry.Value, expected[entry.Key]);
}
}
Downsides to the current approach: file loading is done poorly, and matching keys to values seems like it's way more effort than necessary. Also, I suspect this approach would fall apart with more than one entry in the XML.
I can't imagine that this is the optimal implementation.
© Stack Overflow or respective owner