0

我正在尝试从 xml 制作一个加载器来创建菜单。我的按钮一直有问题。它总是给出空指针的错误。这是代码:title.xml

<?xml version="1.0" encoding="utf-8" ?>
<title>
  <background>Assets/background</background>
  <song>Assets/title</song>
  <button>
    <texture>Assets/background</texture>
    <position>10,10</position>
    <buttonaction>exit</buttonaction>
  </button>
</title>

xmlManager

static public class xmlManager
{
    static public titleData makeTitle(ContentManager content)
    {
        titleData title = new titleData();
        System.IO.Stream stream = TitleContainer.OpenStream("Content/title.xml");
        XDocument doc = XDocument.Load(stream);

        var titleXML = doc.Descendants("title").First();

        title.background = titleXML.Element("background").Value;
        title.song = titleXML.Element("song").Value;

        title.button = new List<Button>();
        title.button = (from button in doc.Element("title").Elements("button")
                            select new Button()
                            {
                                texture = button.Element("texture").Value,
                                position = StringToVector(button.Element("Position").Value),
                                buttonAction = button.Element("buttonAction").Value
                            }).ToList();
        return title;
    }

    static private Vector2 StringToVector(string str)
    {
        //convert a string to a point
        Vector2 vector;
        vector.X = Convert.ToInt32(str.Split(',')[0]);
        vector.Y = Convert.ToInt32(str.Split(',')[1]);
        return vector;
    }
}

它总是在 .xml 管理器中停止select new button()

4

1 回答 1

1

XML 元素名称区分大小写。您buttonaction在 XML 中,但buttonAction在 C# 代码中。

我还建议使用字符串强制转换而不是.Value,因为.Value如果找不到元素会产生 NullReferenceException ,并且这些可能很难追踪:

select new Button()
{
    texture = (string)button.Element("texture"),
    position = StringToVector((string)button.Element("position")),
    buttonAction = (string)button.Element("buttonaction")
}

您还需要修改您的StringToVector()方法以能够处理空值。这将使您的代码对 NullReferenceExceptions 更具弹性。

于 2013-06-23T19:39:13.417 回答