Come convertire treeview in xml?

Sto lavorando su un progetto al momento e ho bisogno di convertire la treeview in xml in modo che possa inviare i dati xml a un’altra porta.

private void button1_Click(object sender, EventArgs e) { var rootElement = new XElement("root", CreateXmlElement(treeView1.Nodes)); var document = new XDocument(rootElement); document.Save("C:\\1.xml"); } private static List CreateXmlElement(TreeNodeCollection treeViewNodes) { var elements = new List(); foreach (TreeNode treeViewNode in treeViewNodes) { var element = new XElement(treeViewNode.Name); if (treeViewNode.GetNodeCount(true) == 1) element.Value = treeViewNode.Nodes[0].Name; else element.Add(CreateXmlElement(treeViewNode.Nodes)); elements.Add(element); } return elements; } 
  Here is the code snippet : public void exportToXml(TreeView tv, string filename) { sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8); sr.WriteLine("< " + tv.Nodes[0].Text + ">"); foreach (TreeNode node in tv.Nodes) { saveNode(node.Nodes); } //Close the root node sr.WriteLine(""); sr.Close(); } private void saveNode(TreeNodeCollection tnc) { foreach (TreeNode node in tnc) { if (node.Nodes.Count > 0) { sr.Write("< " + node.Text + ">"); saveNode(node.Nodes); sr.WriteLine(""); } else sr.Write(node.Text); } }