How do I move XML nodes?
-
I am working on an ASP.NET application using C#. In my XMLDocument, I have a node (that contains other nodes within) that I want to move to another location in the tree. How do move that node AND everything it contains? Is there a MoveNode() method? All I see is a ReplaceChild() method. Will that do the job? The only way I could think of using the ReplaceChild() method is the create a new XMLNode at the new desired location, and then replacing that node with the old one. Then use RemoveChild() to delete the old node. Any better ways? Thanks.
-
I am working on an ASP.NET application using C#. In my XMLDocument, I have a node (that contains other nodes within) that I want to move to another location in the tree. How do move that node AND everything it contains? Is there a MoveNode() method? All I see is a ReplaceChild() method. Will that do the job? The only way I could think of using the ReplaceChild() method is the create a new XMLNode at the new desired location, and then replacing that node with the old one. Then use RemoveChild() to delete the old node. Any better ways? Thanks.
Try something like:
XmlNode MoveNode(XmlNode nodeToMove, XmlNode newParent)
{
// Check we have some values:
if (null == nodeToMove) throw new ArgumentNullException("nodeToMove");
if (null == newParent) throw new ArgumentNullException("newParent");// Are we moving within the same document? if (nodeToMove.OwnerDocument == newParent.OwnerDocument) { // Check that the new parent is not a // child of the node we are moving: XmlNode temp = newParent; while(null != temp) { if (temp == nodeToMove) throw new InvalidOperationException(); temp = temp.ParentNode; } // Remove the node from its old parent: if (null != nodeToMove.ParentNode) nodeToMove.ParentNode.RemoveChild(nodeToMove); // Add the node to the new parent: return newParent.AppendChild(nodeToMove); } else { // Import the node to the new document XmlNode newNode = newParent.OwnerDocument.ImportNode(nodeToMove, true); // Remove the node from its old parent: if (null != nodeToMove.ParentNode) nodeToMove.ParentNode.RemoveChild(nodeToMove); // Add the imported node to the new parent: return newParent.AppendChild(newNode); }
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer