Solved

NullReferenceException was unhandled?

Posted on 2008-10-02
30
707 Views
Last Modified: 2013-12-17
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

0
Comment
Question by:PIER117
  • 10
  • 9
  • 7
  • +2
30 Comments
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 22627877
d.ChildNodes[1] is returning null it looks like ... you might want to look and see what your data actually is.
0
 
LVL 21

Expert Comment

by:silemone
ID: 22627887
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();
0
 
LVL 21

Expert Comment

by:silemone
ID: 22627905
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.
0
 
LVL 11

Expert Comment

by:ladarling
ID: 22627908
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.
0
 
LVL 21

Expert Comment

by:silemone
ID: 22627932
i agree more with that one, ladarling...maybe the second attribute doesn't exist...
0
 
LVL 21

Expert Comment

by:silemone
ID: 22627949
and also greg...oops...at first glance greg, i thought you had  d.ChildNodes[0].InnerText; instead of  d.ChildNodes[1].InnerText;....
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22628205
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
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 22628442
So many comments but they have also all been essentially the same.

The best way is to see the XML though.

Cheers,

Greg
0
 
LVL 1

Author Comment

by:PIER117
ID: 22629189
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

0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 22629394
childnodes[0] contains your user ... what were you expecting to be in childnodes[0]?

Cheers,

Greg
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22629597
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)
0
 
LVL 1

Author Comment

by:PIER117
ID: 22629663
You can not put a string in d.SelectSingleNode().innertext

It has to be an int.

0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22629755
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
0
 
LVL 1

Author Comment

by:PIER117
ID: 22630004
I will try tomorrow.
0
 
LVL 1

Author Comment

by:PIER117
ID: 22638521
still getting the error.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22638573
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
0
 
LVL 1

Author Comment

by:PIER117
ID: 22652806
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
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22657036
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
0
 
LVL 1

Author Comment

by:PIER117
ID: 22699685
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.
0
 
LVL 1

Author Comment

by:PIER117
ID: 22724107
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

0
 
LVL 21

Expert Comment

by:silemone
ID: 22725711
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
0
 
LVL 21

Expert Comment

by:silemone
ID: 22725722
you may have to change your switch to if/else statement however to do this
0
 
LVL 1

Author Comment

by:PIER117
ID: 22726785
silemone,

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

Thanks
0
 
LVL 21

Expert Comment

by:silemone
ID: 22730375
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...
}
0
 
LVL 21

Accepted Solution

by:
silemone earned 25 total points
ID: 22730474
Pseudocode  --- I only did for first, but you have to do for all case statements...because how do you know a firstchild exists?

foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                {
                    foreach (XmlNode innerNode in node.ChildNodes)
                    {
                        switch (innerNode.Name)
                        {
                            case "UniqueID":
                                    try
                                    {
                                             uniqueid = innerNode.FirstChild.Value;           <------even if there is UniqueID how do  
                                    }                                                                                 you know there is a FirstChild?
                                    catch(Exception ex)
                                    {
                                             uniqueid="EMPTY";       <----can give generic value that let's you know doesn't exist
                                             continue;
                                    }
                                    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);
0
 
LVL 26

Assisted Solution

by:Anurag Thakur
Anurag Thakur earned 25 total points
ID: 22731381
you can handle as shown below
XmlDocument doc = new XmlDocument ();

doc.Load (@"C:\abc.xml");
 
 

XmlNodeList UserList;

XmlNodeList ScoreList;

XmlElement root = doc.DocumentElement;

UserList = root.SelectNodes ("/SubAssessmentResponse/User");

ScoreList = root.SelectNodes ("/SubAssessmentResponse/User/SubAssessment");
 

XmlNode node;

for (int i = 0; i < UserList.Count; i++)

{

	node = UserList[i].SelectSingleNode ("UniqueID");
 

	string uniqueid = string.Empty;

	string username = string.Empty;

	if (node != null)

	{

		uniqueid = node.InnerText;

	}

	else

	{

		uniqueid = "some id";

	}

	Console.WriteLine (uniqueid);

	username = UserList[i].SelectSingleNode ("Username").InnerText;

	Console.WriteLine (username);

	foreach (XmlNode f in ScoreList)

	{

		string composite = UserList[i].ChildNodes[0].InnerText;

		Console.WriteLine ("composite : " + composite);

	}

}
 
 

the follwoing is the XML

<?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>

		<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

0
 
LVL 21

Expert Comment

by:silemone
ID: 22732600
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...
0
 
LVL 1

Author Comment

by:PIER117
ID: 22737283
having trouble finding the question you mentioned
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22737385
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
0
 
LVL 1

Author Comment

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

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now