Click to See Complete Forum and Search --> : Looping through ArrayList Class


nickiii
06-26-2007, 02:38 PM
Hi All:

I'm attempting to create a function that reads location information from XML and puts it in an ArrayList. However, I can't seem to print the array results on the screen. When I do, I get this:

--------
System.Collections.ArrayListSystem.Collections.ArrayListSystem.Collections.ArrayList
--------

What am I doing wrong?


Public Function List() As ArrayList

Dim ds As DataSet = New DataSet
Dim xdoc As XmlDataDocument
Dim nodes As XmlNodeList
Dim xnod As XmlNode
Dim locs As ArrayList = New ArrayList

ds.ReadXml("C:\Temp\file.xml")
xdoc = New XmlDataDocument(ds)
nodes = xdoc.DocumentElement.SelectNodes("//ROOT/Report/Location")

For Each xnod In nodes
locs.Add(xnod.InnerText)
Response.Write(locs)
Next

End Function


Thanks!

nickiii
06-26-2007, 02:45 PM
The problem is in my For loop. Trying to recall the VB syntax for this. I know in C++ it's like: for i = 0; i > (whatever); i++

Need2CSharp
06-29-2007, 10:01 AM
Hi nickiii,

I write primarily in C#, but I took a quick look at your code. The way your code is written now, you are printing out the ArrayList object, not the items within the collection. You have a couple options:

1. Simply print out the inner text of your child nodes (ex: Response.Write(xnod.InnerText)) - this probably isn't the option you're looking for, since your return type is ArrayList.

2. Add the inner text to your ArrayList like you are now, and then iterate through the collection after your function call. Also, remove "Response.Write(locs)" from your function; it doesn't have a purpose there:

[After you call the List() function]:

For Each sChildNode as String in ArrayListName
Response.Write(sChildNode)
Next

Hope that helps!

vbrunner
07-06-2007, 04:19 PM
well, part of your problem is the fact that you're using an arraylist in the first place, when it's must easier/smarter to use a System.Collections.Generic.List<T>. That will provide you with the For Each fucntionality you're looking for, as well as some other great stuff. Try this:

Imports System.Collections.Generic
Imports System.Xml

Public Function List() As List(Of String)

Dim ds As DataSet = New DataSet
Dim xdoc As XmlDataDocument
Dim nodes As XmlNodeList
Dim xnod As XmlNode
Dim locs As New List(Of String)

ds.ReadXml("C:\Temp\file.xml")
xdoc = New XmlDataDocument(ds)
nodes = xdoc.DocumentElement.SelectNodes("//ROOT/Report/Location")

For Each xnod In nodes
locs.Add(xnod.InnerText)
Response.Write(locs)
Next

Return locs
End Function