我很难做这个看似简单的任务。我想加载XML文件与加载艺术资产一样容易:XNA:加载和读取XML文件的最佳方法?
content = new ContentManager(Services);
content.RootDirectory = "Content";
Texture2d background = content.Load<Texture2D>("images\\ice");
我不知道如何做到这一点。这tutorial似乎有帮助,但我怎么得到一个StorageDevice
实例?
我有现在一些工作,但感觉很哈克:
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;
}
我将此下面的XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<zombies>
<zombie>
<health>100</health>
<positionX>23</positionX>
<positionY>12</positionY>
<speed>2</speed>
</zombie>
</zombies>
而且它能够通过这个单元测试:
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]);
}
}
目前方法的缺点:文件加载效果不佳,并且键与值匹配就像它比必要的更努力。另外,我怀疑这种方法会在XML中出现多个条目而崩溃。
我无法想象这是最佳实施。
UPDATE:继@Peter Lillevold的建议,我已经改变了这一点:
加载仍然是相当糟糕的,并不知我是不是能够得到单行ToDictionary
与这两个lambda一起工作。我不得不求助于那个foreach循环。我在那里做错了什么?
你有一个错字。我的示例中的@只能与字符串文字一起使用,而不能与字符串变量或参数一起使用。 – 2010-03-14 02:58:24
你知道XNA内容管道ALREADY支持XML文件,不是吗?因此,可以从字面上使用与加载艺术文件来加载XML文件相同的语法。 – 2011-07-05 05:16:27