How to generate an xml from TreeView using C#?

Hi guys,

Here is the sample code for generating xml file from TreeView. I needed this for one of my project. I just referred lot of sites and finally came to conclusion with the following code. Just copy and paste this code and use it for yours.

using System.IO;

private static StreamWriter sr;

private void btnExportXML_Click(object sender, EventArgs e)
{
if (tvXML.Nodes.Count > 0) // Here tvXML is TreeView control
{
sr = new StreamWriter(path); // Here path is xml path
sr.Write("<" + tvXML.Nodes[0].Text + ">");
parseNode(tvXML.Nodes[0]);
sr.Close();
}
}

//Use the following method for getting value of each and every node

private static 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)
{
if (ctn.Tag != null)
{
sr.Write("<" + ctn.Text + ">");
sr.Write(ctn.Tag);
sr.Write("");
}
else
{
sr.Write("<" + ctn.Text + "/>");
}
}
else
{
sr.Write("<" + ctn.Text + ">");
}
if (ctn.GetNodeCount(true) > 0)
{
parseNode(ctn);
}
}
sr.Write("");
sr.WriteLine("");
}

...S.VinothkumaR.

2 comments:

Fırat YILDIRIM said...

it was so useful thx

alj said...

hi vinod,plzz check the following code.It should generate an xml tree,but i am getting a blank html page,can u suggest me a way to resolve this issue.
[WebMethod]
public void hai()
{
XElement root = new XElement("{ericwhite.com}Root"); Console.WriteLine(root);
}
This should generate an xml output on debugging.If not ,please be kind to help me find out my mistake.