title: Inserting XML Fragment after last specific node/element
body: <p>I want to add an XML fragment to the last element to an XML document and I having problems i.e. the error I get is: </p>
  
  <blockquote>
    <p>"The reference node is not a child of
    this node".</p>
  </blockquote>
  
  <p>So my existing XML document looks like this:</p>
  
  <pre><code>&lt;MAP&gt;
    &lt;LAYER name ="My first Layer"&gt;
      &lt;DATASET name="foo dataset" /&gt;
      &lt;SYMBOLOGY&gt; 
        &lt;SYMBOL colour="red" /&gt;
      &lt;/SYMBOLOGY&gt;    
    &lt;/LAYER&gt;
    &lt;LAYER name="My second Layer"&gt;
       &lt;DATASET name="bar dataset" /&gt; 
       &lt;SYMBOLOGY&gt; 
         &lt;SYMBOL colour="blue" /&gt;
       &lt;/SYMBOLOGY&gt;    
    &lt;/LAYER&gt;    
  &lt;/MAP&gt;
  </code></pre>
  
  <p>The XML fragment I want to insert after the last LAYER element is:</p>
  
  <pre><code>&lt;LAYER name="My third Layer"&gt;
       &lt;DATASET name="whatever dataset" /&gt; 
       &lt;SYMBOLOGY&gt; 
         &lt;SYMBOL colour="yellow" /&gt;
       &lt;/SYMBOLOGY&gt;    
  &lt;/LAYER&gt; 
  </code></pre>
  
  <p>The code I am using is:</p>
  
  <pre><code>XmlDocumentFragment xmlDocFrag = xmlDocument.CreateDocumentFragment();
  xmlDocFrag.InnerXml = inputXML; //which is basically the third layer example - see above.
  
  XmlElement rootElement = xmlDocument.DocumentElement;
  XmlNode lastLayerNode = rootElement.SelectSingleNode(@"//LAYER[last()]");
  
  rootElement.InsertAfter(xmlDocFrag, lastLayerNode); //error raised here.
  </code></pre>
  
  <p>Any ideas on what I'm doing wrong here would be much appreciated.  My XPath query seems find and it seems to select the correct last layer it just won't insert after it for some bizarre reason.</p>
  
  <p><strong>UPDATE/SOLUTION - How to do this with XPATH</strong></p>
  
  <p>Finally figured it out in XPath - see the code below, I think it was down to basically not selecting the correct parent node in the first place,  it's incorrect to select the last LAYER then try and InsertAfter() on this node.  Better to select the level above i.e. MAP then AppendChild().  See below:</p>
  
  <pre><code>XmlDocumentFragment xmlDocFrag = xmlDocument.CreateDocumentFragment();
  xmlDocFrag.InnerXml = inputXML;
  
  XmlElement mapElement = (XmlElement)xmlDocument.SelectSingleNode(@"//MAP[last()]");
  mapElement.AppendChild(xmlDocFrag);
  </code></pre>
  
  <p>Thanks to all the replies and help too :)</p>