Link to home
Start Free TrialLog in
Avatar of PIER117
PIER117

asked on

NullReferenceException was unhandled?

I am trying to loop through an xml file and I am getting the error message in the title.  It also says to use the "new" keyword to create an object.  The error occurs on the line with 'string username = d.ChildNodes[1].InnerText;


XmlNodeList UserList;
                XmlNodeList ScoreList;
                XmlElement root = doc.DocumentElement;
                UserList = root.SelectNodes("/SubAssessmentResponse/User");
                ScoreList = root.SelectNodes("/SubAssessmentResponse/User/SubAssessment");
foreach (XmlNode d in UserList)
                {
                    string uniqueid = d.ChildNodes[0].InnerText;
                    string username = d.ChildNodes[1].InnerText;
                    foreach (XmlNode f in ScoreList)
                    {
                        string composite = d.ChildNodes[0].InnerText;
                    }
               ...

Open in new window

Avatar of gregoryyoung
gregoryyoung
Flag of Canada image

d.ChildNodes[1] is returning null it looks like ... you might want to look and see what your data actually is.
place in a try/catch and in catch...print StackTrace for a better error as to which variable is causing this...obviously, you may have set or initialized an object to null and in order to use now you must use Object x = NEW Object();
I would be surprised if that's it greg...if d.childNodes = nothing, then it will just return empty string...plus he's using a foreach loop which should handle if d is null.
The error occurs on the line with 'string username = d.ChildNodes[1].InnerText;
The runtime is telling you that 'd.ChildNodes[1].InnerText' does not exist, that it is not actually referencing an object (your XML node, in this case).
Check to make sure that your XML is well formed. An easy way to see this is to dump it into a datagrid. It could be a nesting problem or something, depending on the source provider.
i agree more with that one, ladarling...maybe the second attribute doesn't exist...
and also greg...oops...at first glance greg, i thought you had  d.ChildNodes[0].InnerText; instead of  d.ChildNodes[1].InnerText;....
sorry after so many comments i am a little confused.
can you please share the xml file and the code so that we can debug the error and respond in a better manner rather than guessing because till the time we know the xml structure we will not know what is actually going wrong
So many comments but they have also all been essentially the same.

The best way is to see the XML though.

Cheers,

Greg
Avatar of PIER117
PIER117

ASKER

I've included the xml.  When the error display, Visual Studio shows data on that node when I place my mouse over it.  Am I looping through the XML correctly?  SubAssessment is a child of User, but it is also contains nodes.


  <?xml version="1.0" encoding="utf-8" ?> 
- <SubAssessmentResponse>
- <User>
  <UniqueID>100000</UniqueID> 
  <Username>test@yahoo.com</Username> 
- <SubAssessment>
  <Composite>79</Composite> 
  <ClassroomManagement>78</ClassroomManagement> 
  <TeachingStrategies>73</TeachingStrategies> 
  <LegalEducation>75</LegalEducation> 
  <PreparedProfessional>90</PreparedProfessional> 
  <FillInActivities>80</FillInActivities> 
  </SubAssessment>
  </User>- <User>
  <UniqueID>100002</UniqueID> 
  <Username>test2@yahoo.com</Username> 
- <SubAssessment>
  <Composite>79</Composite> 
  <ClassroomManagement>78</ClassroomManagement> 
  <TeachingStrategies>73</TeachingStrategies> 
  <LegalEducation>75</LegalEducation> 
  <PreparedProfessional>90</PreparedProfessional> 
  <FillInActivities>80</FillInActivities> 
  </SubAssessment>
  </User>
</SubAssessmentResponse>

Open in new window

childnodes[0] contains your user ... what were you expecting to be in childnodes[0]?

Cheers,

Greg
your code worked perfectly with the sample xml provided by you
no exceptions etc

but i found one thing in your code which i didnt like - i will recommend you to change the follwoing 2 lines to
string uniqueid = d.ChildNodes[0].InnerText;
string username = d.ChildNodes[1].InnerText;

to

string uniqueid = d.SelectSingleNode("UniqueID").InnerText;
string username = d.SelectSingleNode("Username").InnerText

similarly do the change for composite section too

the reason for error might be that the childnodes[1] did not exist in your xml (thats the only thing i can think of)
Avatar of PIER117

ASKER

You can not put a string in d.SelectSingleNode().innertext

It has to be an int.

please try my code it works
i have already tried out and i have been using selectsinglenode and selectnodes with string since the time i have started playing with xml

the code will work perfectly, just give it a try
Avatar of PIER117

ASKER

I will try tomorrow.
Avatar of PIER117

ASKER

still getting the error.
in that case i will simply say that the xml that you provided us works fine with the code that even you wrote or i recommended
need to be a little more elobaritive on what the error is - then only we can be useful with our thoughts
Avatar of PIER117

ASKER

Well, I'm not sure what the problem is.  The error displays on the first node I tried to grab information from.  It says the node is null, but when I put my mouse over the code it displays information from the xml document.  I've attached a screenshot of the error messge.
error.bmp
We have tried you xml and your code and found that both are correct
if you still getting the exception then I think that there is still something which you need to communicate to us
Avatar of PIER117

ASKER

I'm still getting the error message.  I'm assuming that there is something in the received xml that is triggering the error.  The code reaches a certain record and then the error displays.  I do not have access to the code where I am current at.  I will post a copy on tuesday.
Avatar of PIER117

ASKER

Ok, found the issue, but don't know how to resolve it.  I'm hitting a node that doesn't exist for some users.  Some older users do not have data in the UniqueID node.  I can correct this later by temporarily putting in a generic number for now.  How do I do that?  or is there a better way to handle it?
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                {
                    foreach (XmlNode innerNode in node.ChildNodes)
                    {
                        switch (innerNode.Name)
                        {
                            case "UniqueID":
                                    uniqueid = innerNode.FirstChild.Value;
                                    break;
                            case "Username":
                                username = innerNode.FirstChild.Value;
                                break;
                            case "SubAssessment":
                                foreach (XmlNode assessmentNode in innerNode.ChildNodes)
                                {
                                    if (assessmentNode.Name == "Composite")
                                        composite = assessmentNode.FirstChild.Value;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    loadDesigner2(ds, uniqueid, username, composite);

Open in new window

use an internal try/catch statement that will just continue the loop...

i.e. it can't be a try/catch around the entire foreach statement, use a try/catch that will continue to next loop if exception occurs
you may have to change your switch to if/else statement however to do this
Avatar of PIER117

ASKER

silemone,

Can you give me an example I'm very new at this?

Thanks
which node is causing problem?  just add a try/catch block around that node...

i.e.

pseudocode


try
{
        //place code that's causing error in here        

}
catch(Exception ex)
{
          ex.StackTrace.ToString()        //Can create an error log with is...place in a file that you can read app execution
          continue;           //will cause loop to continue, but to the next node if one doesn't exist...
}
ASKER CERTIFIED SOLUTION
Avatar of silemone
silemone
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
rag used the if/else way i suggested at ID:22725711 to test if node is null but I used the try/catch way so i wouldn't have to change your code around too much...as i suggested you may have to change switch to if/else statements...
Avatar of PIER117

ASKER

having trouble finding the question you mentioned
i just gave the solution - the solution which handles whether the user id is there or not now it depends on the author to do whatever way they feel like do
i do it using the for loop because its better and faster than the for each loop and i always perfer it over the for each
ID:22731381
Avatar of PIER117

ASKER

This may be silly, but I can't find a place to plug in the id# to find the topic you are referencing.