title: Save TreeView as xml with attributes and elements
body: <p>I have a Windows Forms TreeView that needs to be saved as a xml file.</p>
  
  <p>The structure of the TreeView is like this:</p>
  
  <pre><code> - Parent
    - Child 1 (Any value)
    - Child 2
      - Child 1 (Any value for a child)
  </code></pre>
  
  <p>Every TreeNode that has children needs to be saved as a element, and every TreeNode that does not have children needs to be saved as a attribute to it's parent TreeNode</p>
  
  <p>This means the above would result in the following xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;Parent Child1="Any value"&gt;
    &lt;Child2 Child1="Any value for a child" /&gt;
  &lt;/Parent&gt;
  </code></pre>
  
  <p>I tried using the following code, but it did not work when the TreeNodes with no children where below the TreeNodes with children and I couldn't really figure out a good way of doing it.</p>
  
  <pre><code>    public void SerializeTreeView(TreeView treeView, string fileName)
      {
          XmlWriterSettings settings = new XmlWriterSettings();
          settings.Indent = true;
  
          XmlWriter textWriter = XmlWriter.Create(fileName, settings);
  
          // Writing the xml declaration tag
          textWriter.WriteStartDocument();
  
          // Save the nodes, recursive method
          SaveNodes(treeView.Nodes, textWriter);
  
          // End the xml document
          textWriter.WriteEndDocument();
          textWriter.Close();
      }
  
      private void SaveNodes(TreeNodeCollection nodesCollection, XmlWriter textWriter)
      {
          for (int i = 0; i &lt; nodesCollection.Count; i++)
          {
              TreeNode node = nodesCollection[i];
  
              if (node.Nodes.Count &gt; 0)
              {
                  textWriter.WriteStartElement(node.Name);
              }
              else
              {
                  textWriter.WriteAttributeString(node.Name, "Attribute value");
              }
  
              if (node.Nodes.Count &gt; 0)
                  SaveNodes(node.Nodes, textWriter);
  
              if (node.Nodes.Count &gt; 0)
                  textWriter.WriteEndElement();
          }
      }
  </code></pre>
  
  <p><strong>EDIT:</strong> </p>
  
  <p>The problem with the current code is that if I add a TreeNode that has any children and is ABOVE a TreeNode with no children, it gives me the following error:</p>
  
  <pre><code>Token StartAttribute in state Element Content would result in an invalid XML document.
  </code></pre>
  
  <p>This happens at:</p>
  
  <pre><code>textWriter.WriteAttributeString(node.Name, "Attribute value");
  </code></pre>
  
  <p>I solved it by sorting the TreeView by child node count (Meaning that the TreeNode with NO children will ALWAYS be below a TreeNode without children)</p>
  
  <p>The solution works, but I would like to figure out why the error occurred and how to fix it.</p>