Parse your XML and depending on what XML elements you want as nodes add them:
var xmlSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<factors>
<factor number=""1"" price=""1000"">
<code>12</code>
<group>A</group>
</factor>
<factor number=""2"" price=""10"">
<code>1</code>
<group>B</group>
</factor>
</factors>";
var xml = XDocument.Parse(xmlSource);
var factors = xml.Root.Descendants("factor").ToList();
// create tree and add root node
// TreeView tr = new TreeView();
// var root = tr.Nodes.Add("Factors");
foreach (var factor in factors)
{
var nodeNumber = factor.Attribute("number").Value;
var subNodeCode = factor.Element("code").Value;
// add attribute as node name
// var node = root.Nodes.Add(nodeNumber);
// add elements as sub nodes
// node.Nodes.Add(subNodeCode)
}
The code for saving from the tree to XML is exactly the same, just in the oposite direction - iterate through all nodes and extract and build the xml elements and/or attributes. You should know best which element or attribute you want to show as tree node and vice versa.
Read the documentation for the TreeView class and LINQ2XML starting for example from the XDocument helper class
Assuming that your TreeView is named tree, then with the following code you can create quickly a XML document from the nodes:
var xml = new XDocument();
var rootElement = new XElement("factors");
foreach (TreeNode node in tree.Nodes)
{
foreach (TreeNode subNode in node.Nodes)
{
var attribute = new XAttribute("number", subNode.Text);
var element = new XElement("factor", attribute);
foreach (TreeNode subSubNode in subNode.Nodes)
{
var subElement = new XElement("code", subSubNode.Text);
element.Add(subElement);
}
rootElement.Add(element);
}
}
xml.Add(rootElement);
xml.ToString(); // gives you the XML code
// OR save the XML directly to file
//xml.Save(@"c:\temp\output.xml");
Far better and efficient would be to write a recursive function that gives you filled XElement object back. You should also use the Tag TreeNode property to store the information for every TreeNode.