title: Adding and manipulating multiple child nodes using XPathNavigator in C#
body: <p>I'm writing classes which (de)serialize to/from XML. When serializing and deserializing, the class gets a XPathNavigator to get data from/add data to.</p>
  
  <p>Because the class may contain objects which are need to be serialized too (using the same mechanism), I do the following to add a child element for each object:</p>
  
  <pre><code>public void Serialize(XPathNavigator navigator)
  {
  
      foreach(IXmlSerializableObject o in objects) {
  
          // Create child element.
          navigator.AppendChildElement(string.Empty, "child", string.Empty, null);
  
          // Move to last child element.
          navigator.MoveToChild(XPathNodeType.Element);
          while (navigator.MoveToNext(XPathNodeType.Element)) ;
  
          // Serialize the object at the current node.
          // This will add attributes and child elements as required.
          // The navigator will be positiononed at the same node after the call.
          o.Serialize(navigator);
  
          navigator.MoveToParent();
      }
  
  }
  </code></pre>
  
  <p>Especially the MoveToParent/Move to last child part seems to be awfully wrong (though it works). Is there a better way to do this?</p>
  
  <p>Another approach I use (to avoid that objects get access to information stored so far) is this:</p>
  
  <pre><code>foreach(IXmlSerializableObject o in objects) {
  {
  
      // Create a new (empty) document for object serialization.
      XPathNavigator instructionNavigator = new XmlDocument().CreateNavigator();
      instructionNavigator.AppendChildElement(string.Empty, "child", string.Empty, null);
      instructionNavigator.MoveToChild(XPathNodeType.Element);
  
      // Serialize the object.
      o.Serialize(instructionNavigator);
  
      // Now add the serialized content to the navigator.
      instructionNavigator.MoveToRoot();
      instructionNavigator.MoveToChild(XPathNodeType.Element);
      navigator.AppendChild(instructionNavigator);
  }
  </code></pre>
  
  <p>Both approaches seem to be somehow circumstantial as they both create lots of overhead. I would appriciate any ideas or hints on how to improve my algorithm. </p>
  
  <p>greetings,
  Dominik</p>