XNA:读取和加载XML文件的最佳方法是什么?

7

我在做这个看似简单的任务时遇到了困难。我希望能够像加载艺术资源一样轻松地加载XML文件:

        content  = new ContentManager(Services);
        content.RootDirectory = "Content";
        Texture2d background = content.Load<Texture2D>("images\\ice");

我不确定该怎么做。这个教程看起来很有帮助,但我如何获得StorageDevice实例呢?
我现在有一些可用的东西,但感觉相当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;
        }

我将对以下XML文件进行操作:

我将对以下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中有多个条目时崩溃。我无法想象这是最佳实现。
更新:在@Peter Lillevold的建议下,我做了些改变:
    public IDictionary<string, string> Get(string typeName)
    {
        IDictionary<String, String> result = new Dictionary<String, String>();

        IEnumerable<XElement> zombieValues = root.Element(@typeName).Elements();

        //result["health"] = zombie.Element("health").ToString();

        IDictionary<string, XElement> nameToElement = zombieValues.ToDictionary(element => element.Name.ToString());

        foreach (KeyValuePair<string, XElement> entry in nameToElement)
        {
            result[entry.Key] = entry.Value.FirstNode.ToString();
        }

        return result;
    }

    public ReadWriteXML(string uri)
    {
        root = XElement.Load(uri);
    }

    internal virtual IPersistentState CreateIPersistentState(string fullpath)
    {
        return new ReadWriteXML(fullpath);
    }

    /// <summary>
    ///A test for Get with one zombie.
    ///</summary>
    [TestMethod()]
    public void SimpleGetTest()
    {
        IPersistentState target = CreateIPersistentState("../../../path/Data/SavedZombies.xml");
        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, actual[entry.Key]);
        }
    }

加载仍然相当糟糕,而且某种方式我无法让单行的ToDictionary与这两个lambda函数一起使用。我不得不求助于那个foreach循环。我在做什么错了吗?


你在那里有一个打字错误。我的示例中的@只能与字符串文字一起使用,而不能与字符串变量或参数一起使用。 - Peter Lillevold
1
你知道XNA内容管道已经支持XML文件了吗?所以你可以使用加载艺术文件的相同语法来加载XML文件。 - BlueRaja - Danny Pflughoeft
2个回答

8

还有一个新的、闪亮的XElement(它支持Linq to XML)。这个示例将加载一个xml文件,查找zombie并将值转储到一个字典中:

var doc = XElement.Load("filename");
var zombieValues = doc.Element("zombie").Elements();
var zombieDictionary = 
    zombieValues.ToDictionary(
        element => element.Name.ToString(), 
        element => element.Value);

如果您更愿意明确选择每个值(并使用转换来自动转换为适当的值类型),则可以执行以下操作:

var zombie = doc.Element("zombie");
var health = (int)zombie.Element("health");
var positionX = (int)zombie.Element("positionX");
var positionY = (int)zombie.Element("positionY");
var speed = (int)zombie.Element("speed");

更新:修正了一些错别字并进行了一些清理,你的Get方法应该像这样:

public IDictionary<string, string> Get(string typeName)
{
    var zombie = root.Element(typeName);
    return zombie.Elements()
          .ToDictionary(
                  element => element.Name.ToString(),
                  element => element.Value);
}

而“@”符号在“zombie”前面有什么意义呢? - Nick Heiner
另外,我如何以更优雅的方式加载文件而不是使用URI?(例如内容管道) - Nick Heiner
抱歉,在这里不需要使用 @。它用于在字符串前缀时,表示该字符串应该是逐字的。 您可以查看如何为您的文件类型创建自定义管道处理器。请参阅:http://msdn.microsoft.com/en-us/library/bb447754.aspx - Peter Lillevold
我认为其中一个.Elements()调用是多余的。但除此之外,这使得我的代码显著更清晰。 - Nick Heiner

2
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlString);

string health = doc["zombies"]["zombie"]["health"].InnerText;
// etc..

// or looping

foreach( XmlNode node in doc["zombies"].ChildNodes )
{
    string health = node["health"].InnerText;
    // etc...
}

那在XNA中不行吗?


我会尝试这样做。但是,首先从文件中获取xmlString有更好的方法吗? - Nick Heiner
更新了代码,因为我犯了一个错误。(doc.Load => doc.LoadXml) - FallenAvatar
似乎XmlDocument在.NET的XNA分发中没有包含,或者至少当我尝试使用它时会出现错误。 - Arkiliknam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接