Moving an XML Node Up or Down Using C Sharp

To move an xml node up in a document you can use the following code.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = false;xmlDocument.Load(@"file.xml");
XmlNode fieldNode = xmlDocument.SelectSingleNode(@"/root/field[@name = '3']");

if (fieldNode != null) {
fieldNode.ParentNode.InsertBefore(fieldNode,
fieldNode.PreviousSibling);
}

// save changes somewhere
// in this example simply the console to show changes
xmlDocument.Save(Console.Out);

To move an xml nut up in a document you can use the following code. You can do the same for moving it down using InsertAfter.

Bookmark and Share