473,387 Members | 1,545 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

foreach loop confusion

Art
Hello,
Here is a fragment of my code, which fails and I don't know why.
---------------------------------
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\mydoc.xml");
foreach (XmlNode objNode in doc.SelectNodes("author"))
{
System.WriteLine(objNode.Value.ToString());
}
---------------------------------------------------------------
I get an error saying that objNode is not set to XmlNode. I step thru code and surely enough it is not - why?
Nov 16 '05 #1
9 6133
Art,

Can you post the document that you are parsing and scanning through?
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Art" <Ar*@discussions.microsoft.com> wrote in message
news:17**********************************@microsof t.com...
Hello,
Here is a fragment of my code, which fails and I don't know why.
---------------------------------
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\mydoc.xml");
foreach (XmlNode objNode in doc.SelectNodes("author"))
{
System.WriteLine(objNode.Value.ToString());
}
---------------------------------------------------------------
I get an error saying that objNode is not set to XmlNode. I step thru code and surely enough it is not - why?

Nov 16 '05 #2
foreach loop is a beautiful concept which saves lotsa headache and
unnecessary variable assignments. This is the quickest way to iterate a
collection. However, please keep in mind the following

1. You cannot remove a value from the collection while reading
2. You cannot add values while reading
3. You cannot refresh values while reading

To solve ur problem do this.

XmlNodeList nList = doc.SelectNodes("author");

foreach (XmlNode objNode in nList)
{
System.WriteLine(objNode.Value.ToString());
}
//note: the following code will throw execption
foreach (XmlNode objNode in nList)
{
nList.Remove(0); //Collection value cannot be modified
nList.Add(newNode);//collection value cannot be modified.
}

Shak.

"Art" <Ar*@discussions.microsoft.com> wrote in message
news:17**********************************@microsof t.com...
Hello,
Here is a fragment of my code, which fails and I don't know why.
---------------------------------
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\mydoc.xml");
foreach (XmlNode objNode in doc.SelectNodes("author"))
{
System.WriteLine(objNode.Value.ToString());
}
---------------------------------------------------------------
I get an error saying that objNode is not set to XmlNode. I step thru code and surely enough it is not - why?

Nov 16 '05 #3
Shakir Hussain <sh***********@hotmail.com> wrote:
foreach loop is a beautiful concept which saves lotsa headache and
unnecessary variable assignments. This is the quickest way to iterate a
collection. However, please keep in mind the following

1. You cannot remove a value from the collection while reading
2. You cannot add values while reading
3. You cannot refresh values while reading

To solve ur problem do this.

XmlNodeList nList = doc.SelectNodes("author");

foreach (XmlNode objNode in nList)
{
System.WriteLine(objNode.Value.ToString());
}


That shouldn't in any way affect the code which was posted, however, as
the posted code didn't change the collection.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
Art <Ar*@discussions.microsoft.com> wrote:
Here is a fragment of my code, which fails and I don't know why.
---------------------------------
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\mydoc.xml");
foreach (XmlNode objNode in doc.SelectNodes("author"))
{
System.WriteLine(objNode.Value.ToString());
}
---------------------------------------------------------------
I get an error saying that objNode is not set to XmlNode. I step thru
code and surely enough it is not - why?


Could you post the *exact* error message? A short but complete example
(including the XML file) would be helpful, too.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Art
Shak,
I'm going to try your suggestion as I'm not trying to modify XML file here - just reading the values, which will go into DataTable.

"Shakir Hussain" wrote:
foreach loop is a beautiful concept which saves lotsa headache and
unnecessary variable assignments. This is the quickest way to iterate a
collection. However, please keep in mind the following

1. You cannot remove a value from the collection while reading
2. You cannot add values while reading
3. You cannot refresh values while reading

To solve ur problem do this.

XmlNodeList nList = doc.SelectNodes("author");

foreach (XmlNode objNode in nList)
{
System.WriteLine(objNode.Value.ToString());
}
//note: the following code will throw execption
foreach (XmlNode objNode in nList)
{
nList.Remove(0); //Collection value cannot be modified
nList.Add(newNode);//collection value cannot be modified.
}

Shak.

"Art" <Ar*@discussions.microsoft.com> wrote in message
news:17**********************************@microsof t.com...
Hello,
Here is a fragment of my code, which fails and I don't know why.
---------------------------------
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\mydoc.xml");
foreach (XmlNode objNode in doc.SelectNodes("author"))
{
System.WriteLine(objNode.Value.ToString());
}
---------------------------------------------------------------
I get an error saying that objNode is not set to XmlNode. I step thru code

and surely enough it is not - why?


Nov 16 '05 #6
Art <Ar*@discussions.microsoft.com> wrote:
The above is the exact structure I'm working with. More, I was trying
to extract all the "filename" nodes and just print their values like
this:

XmlDocument doc = new XmlDocument(); - I'm OK here
doc.Load <above XML file:>; - I'm OK here
foreach (XmlNode objNode in doc.SelectNodes("//textfiles/files/filename"))
{
System.WriteLine(objNode.Value.ToString()) - Failure here
// Error - Object reference not set to an instance of an object
}


Ah, that's not the error you talked about before. That sounds like a
NullReferenceException, which just means that objNode.Value is null.
(Assuming objNode itself isn't null, which seems unlikely to me.)

It's entirely reasonable that objNode.Value is null, however, as you'll
have selected a load of elements, and (as the documentation for
XmlNode.Value states) the Value of an element is null.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
Art,

I don't see an author element or attribute there, so perhaps the
SelectNode method is returning null (which would definitely cause an
exception).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Art" <Ar*@discussions.microsoft.com> wrote in message
news:0F**********************************@microsof t.com...
Nicholas,
The document is rather large but here is an excerpt:
------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<config>
<textfiles>
<files path="/">
<filename att1="1" att2="2">file1.txt</filename>
{lots more nodes like <filename>}
</files>
<files path="/Secure">
<filename att1="1" att2="2">file1.txt</filename>
{lots more nodes like <filename>}
</files>
{lots more nodes like <files>}
</textfiles>
</config>
----------------------------------------------

The above is the exact structure I'm working with. More, I was trying to extract all the "filename" nodes and just print their values like this:
XmlDocument doc = new XmlDocument(); - I'm OK here
doc.Load <above XML file:>; - I'm OK here
foreach (XmlNode objNode in doc.SelectNodes("//textfiles/files/filename"))
{
System.WriteLine(objNode.Value.ToString()) - Failure here
// Error - Object reference not set to an instance of an object
}

I have also tried iterating via for loop and using index in NodeList.Item(i).Value etc. but the result was the same.
Art

"Nicholas Paldino [.NET/C# MVP]" wrote:
Art,

Can you post the document that you are parsing and scanning through?

Nov 16 '05 #8
Art
John,
Yes, your suggestion was right on a target. What I should have done was to use "InnerText" property to get a text value for that node instead of ".Value.ToString()", which really was null.
Art

"Jon Skeet [C# MVP]" wrote:
Art <Ar*@discussions.microsoft.com> wrote:
The above is the exact structure I'm working with. More, I was trying
to extract all the "filename" nodes and just print their values like
this:

XmlDocument doc = new XmlDocument(); - I'm OK here
doc.Load <above XML file:>; - I'm OK here
foreach (XmlNode objNode in doc.SelectNodes("//textfiles/files/filename"))
{
System.WriteLine(objNode.Value.ToString()) - Failure here
// Error - Object reference not set to an instance of an object
}


Ah, that's not the error you talked about before. That sounds like a
NullReferenceException, which just means that objNode.Value is null.
(Assuming objNode itself isn't null, which seems unlikely to me.)

It's entirely reasonable that objNode.Value is null, however, as you'll
have selected a load of elements, and (as the documentation for
XmlNode.Value states) the Value of an element is null.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
Art
Nicholas,
Sorry about the confusion related to XML ... I have been looking on the web for examples on how to do this and lots of places had the typical author/title XML sample file. I guess I quoted what was just on my mind.
Thanks for your time and help. Problem was related to Node.Value vs. Node.InnerText property. I thought that Value would give you text value of a node which was not the case.
Thanks.

"Nicholas Paldino [.NET/C# MVP]" wrote:
Art,

I don't see an author element or attribute there, so perhaps the
SelectNode method is returning null (which would definitely cause an
exception).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Art" <Ar*@discussions.microsoft.com> wrote in message
news:0F**********************************@microsof t.com...
Nicholas,
The document is rather large but here is an excerpt:
------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<config>
<textfiles>
<files path="/">
<filename att1="1" att2="2">file1.txt</filename>
{lots more nodes like <filename>}
</files>
<files path="/Secure">
<filename att1="1" att2="2">file1.txt</filename>
{lots more nodes like <filename>}
</files>
{lots more nodes like <files>}
</textfiles>
</config>
----------------------------------------------

The above is the exact structure I'm working with. More, I was trying to

extract all the "filename" nodes and just print their values like this:

XmlDocument doc = new XmlDocument(); - I'm OK here
doc.Load <above XML file:>; - I'm OK here
foreach (XmlNode objNode in doc.SelectNodes("//textfiles/files/filename"))
{
System.WriteLine(objNode.Value.ToString()) - Failure here
// Error - Object reference not set to an instance of an object
}

I have also tried iterating via for loop and using index in

NodeList.Item(i).Value etc. but the result was the same.

Art

"Nicholas Paldino [.NET/C# MVP]" wrote:
Art,

Can you post the document that you are parsing and scanning through?


Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Randell D. | last post by:
Folks, Ever since reading an interesting article in Linux Format on PHP whereby suggested code writing was made that could enhance performance on a server, I've started testing various bits of...
104
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars...
32
by: Joe Rattz | last post by:
Hmmm, I wrote the following code. I want an array of bools and I want to intialize them to false. bool bits = new bool; foreach(bool bit in bits) { bit = false; } The compiler complains...
15
by: Mike Lansdaal | last post by:
I came across a reference on a web site (http://www.personalmicrocosms.com/html/dotnettips.html#richtextbox_lines ) that said to speed up access to a rich text box's lines that you needed to use a...
13
by: TrintCSD | last post by:
How can I reset the collections within a foreach to be read as a change from within the foreach loop then restart the foreach after collections has been changed? foreach(string invoice in...
4
by: Sjoerd | last post by:
Summary: Use foreach(..) instead of while(list(..)=each(..)). --==-- Foreach is a language construct, meant for looping through arrays. There are two syntaxes; the second is a minor but useful...
3
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current...
2
by: recordlovelife | last post by:
So I am trying to display a title, date, and content of a wordpress blog. Word press provides nice drop in functions to get the job done with simple names like "the_title", and the "the_content" But...
7
by: Osiris | last post by:
Just something I would like to share: I just learned the hard way (2 days detective work on a bug) that foreach loops are not at all like for loops, not intuitive at all. BEWARE: arrays and...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.