title: Can't Insert New Element Into XML Tree
body: <p>I am attempting to create an <code>XmlElement</code> and insert it as a <strong>sibling</strong> after an existing element. Here is the existing element:</p>
  
  <pre><code>&lt;!--     other XHTML  precedes this --&gt;
           &lt;p id="testElement"&gt;Test element&lt;/p&gt;
  &lt;!--     other XHTML follows this  --&gt;
  </code></pre>
  
  <p>The document contains only one <code>p</code> element like the above.
  Here is the element I want to add after the <code>p</code> element:</p>
  
  <pre><code>&lt;div class=”CodeChar”&gt;
    &lt;pre/&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I want the resulting XHTML to look like this:</p>
  
  <pre><code>&lt;!--     other XHTML  precedes this --&gt;
           &lt;p id="testElement"&gt;Test element&lt;/p&gt;
           &lt;div class=”CodeChar”&gt;
              &lt;pre/&gt;
           &lt;/div&gt;
  &lt;!--     other XHTML follows this  --&gt;
  </code></pre>
  
  <p>I’m using the following lines of code to get a reference to the <code>p</code> element and add the div:</p>
  
  <pre><code>XmlElement selectedElement = null;
  XmlNodeList elts = xmlDoc.GetElementsByTagName("p");
  foreach (XmlElement elt in elts)
  {
      String val = elt.GetAttribute("id");
      if (val.Equals("testElement"))
      {
          selectedElement = elt;
          break;
      }
  }
  
  if (selectedElement == null)
  {
      return;
  }
  
  XmlElement newDivElement = xmlDoc.CreateElement("div");
  newDivElement.SetAttribute("class", "CodeChar");
  XmlElement preNode = xmlDoc.CreateElement("pre");
  newDivElement.AppendChild( preNode );
  xmlDoc.InsertAfter(newDivElement, selectedElement);
  </code></pre>
  
  <p>However, the last line in the above code yields an an exception that says <code>“The reference node is not a child of this node.”</code> 
  Thanks</p>