在xml中访问多个对象时的空引用c#

时间:2013-06-23 17:58:27

标签: c# xml xna xna-4.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;
    }
}

它始终在select new button()的xml管理器内停止。

1 个答案:

答案 0 :(得分:1)

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

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

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

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