what is the valid argument for IEnumerator on TreeNode?
i got the error on this line:
IEnumerator ie = tn.Nodes.GetEnumerator();
in this method:
private void parseNode(TreeNode tn)
{
IEnumerator ie = tn.Nodes.GetEnumerator();
string parentnode = "";
parentnode = tn.Text;
while (ie.MoveNext())
{
TreeNode ctn = (TreeNode)ie.Current;
if (ctn.GetNodeCount(true) == 0)
{
_nodeToString += ctn.Text;
}
else
{
_nodeToString += "<" + ctn.Text + ">";
}
if (ctn.GetNodeCount(true) > 0)
{
parseNode(ctn);
}
}
_nodeToString += "</" + parentnode + ">";
_nodeToString += "\n";
}
(from comments)
Using the generic type 'System.Collections.Generic.IEnumerator' requires '1' type arguments
That means you have
using System.Collections.Generic;
and not
using System.Collections;
switch to the latter and it will work. IEnumerable
/ IEnumerator
are the non-generic API.
Or better: use foreach
- it is simpler, safer and more correct (you didn't remember to check for IDisposable
, for example).
Additional notes:
StringBuilder
is preferred by a long marginXmlWriter
would be idealso IMO: use an XmlWriter
that writes to a StringBuilder
, using foreach
Untested, but something like:
private string parseNode(TreeNode tn)
{
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb))
{
writer.WriteStartElement("xml");
parseNode(tn, writer);
writer.WriteEndElement();
}
return sb.ToString();
}
private void parseNode(TreeNode tn, XmlWriter writer)
{
if (tn.Nodes.Count > 0)
{
writer.WriteStartElement(tn.Text);
foreach (TreeNode child in tn.Nodes)
{
parseNode(child, writer);
}
writer.WriteEndElement();
}
else
{
writer.WriteString(tn.Text);
}
}