Quote:
Originally Posted by Rooster2
It is giving me the Null Reference Exception. The number reported counts up per click, and originally started at 3 and I tried a few times, so at about 7 now. There are 19 current tips.. tipsXML.xml file looks as such:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<tip>this is tip 0</tip>
<tip>this is tip 1</tip>
<tip>this is tip 2</tip>
<tip>this is tip 3</tip>
<tip>this is tip 4</tip>
<tip>this is tip 5</tip>
<tip>this is tip 6</tip>
<tip>this is tip 7</tip>
<tip>this is tip 8</tip>
<tip>this is tip 9</tip>
<tip>this is tip 10</tip>
<tip>this is tip 11</tip>
<tip>this is tip 12</tip>
<tip>this is tip 13</tip>
<tip>this is tip 14</tip>
<tip>this is tip 15</tip>
<tip>this is tip 16</tip>
<tip>this is tip 17</tip>
<tip>this is tip 18</tip>
<tip>this is tip 19</tip>
</root>
I did have that N-1 line at the end (wasn't sure what N-1 meant, if it should be there, etc..) It did the same thing..
|
Ok, I can see the problem now, the first child in your XML file is the XML declaration, we need to choose the first ELEMENT in the document instead
So, we change the method like this:
Code:
private string getTipFromNumber(int number)
{
//first go to the root, get the tip based on number between 0 and N-1, get the inner text (the tip itself).
if (tipsXML == null) //if we don't have a valid xml document open
Console.WriteLine("I don't have an xml file to read.");
else if (tipsXML.DocumentElement == null) //if our xml document doesn't have a root element (aka first ELEMENT child)
Console.WriteLine("The XML document doesn't have a root element.");
else if (tipsXML.DocumentElement.ChildNodes.Count <= number || number < 0) //make sure the number we received is between 0 and the childs count minus 1 for last child.
{
Console.WriteLine("I don't have a tip number: '" + number + "' in the XML file.");
Console.WriteLine("I can accept only tips from '0' to '" + (tipsXML.DocumentElement.ChildNodes.Count - 1) + "'.");
}
else //everything seems to be ok, return the message
return tipsXML.DocumentElement.ChildNodes[number].InnerText;
//if we reached this point than we have a problem.
//in real programming we'll throw an invalid arguments exception and let the program crash.
throw new ArgumentException("Unable to access tip number '"+number+"'.");
//but if you don't want to crash for some weired reason (like RunUO scripting) you just return an error string back:
//return "NULL REFERENCE EXCEPTION WAS PREVENTED while trying to access tip '" + number + "', please contact the administrator and report this message and the number '" + number + "'.";
//Only have ONE option enabled and the other marked out, either throw the exception (real programmer) or return the bad message ("programming for kids"), don't have both lines active (without remarks) at the same time or you'll get "unreachable code detected" warning!
}