Are you sure that xmlNode
is returning the node you think it is? Step through it with the debugger.
If it is null
, then the node you insert will get added as a child of the DocumentElement
as you describe. If it is returning the Pages node, then you should get an exception 'The reference node is not a child of this node'.
This is fairly self explanatory. The code:
doc.DocumentElement.InsertAfter(xNewChild, xmlNode);
should be:
xmlNode.ParentNode.InsertAfter(xNewChild, xmlNode);
This said, if possible I'd be using XDocument
, a part of XLinq. The API's a lot nicer & more powerful, and is generally higher performance. An example:
var element = x.Descendants("Pages").Single(e => e.Attribute("PageContentID").Value == "206");
var newElement = new XElement("Pages",
new XAttribute("Name", "Another New Page"),
new XAttribute("PageContentID", Guid.NewGuid().ToString()),
new XAttribute("Template", "ReportTags"));
element.AddAfterSelf(newElement);