How to convert treeview to xml?
I am working on a project cur开发者_Python百科rently and I need to convert the treeview to xml so that I can send that xml data to another port.
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<XElement> CreateXmlElement(TreeNodeCollection treeViewNodes)
{
var elements = new List<XElement>();
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("</" + tv.Nodes[0].Text + ">");
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("</" + node.Text + ">");
}
else
sr.Write(node.Text);
}
}
精彩评论