null refference at acessing multiple object in xml wit c#

I'm trying to make a loader from xml to create menu. I have been having problem with the button. It always gives an error of null pointer. Here is the code: 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;
    }
}

It always stops inside the xml manager at the select new button().

Upvotes: 0

Views: 79

Answers (1)

JLRishe
JLRishe

Reputation: 101682

XML element names are case sensitive. You have buttonaction in your XML, but buttonAction in your C# code.

I would also recommend using string casts instead of .Value, as .Value will produce a NullReferenceException if an element is not found, and these can be hard to track down:

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

You would also need to modify your StringToVector() method to be able to handle null values. This will make your code more resilient against NullReferenceExceptions.

Upvotes: 1

Related Questions