Given an XML structure like this:
<garage>
<car>Firebird</car>
<car>Altima</car>
<car>Prius</car>
</garage>
I want to "move" the Prius node "one level up" so it appears above the Altima node. Here's the final structure I want:
<garage>
<car>Firebird</car>
<car>Prius</car>
<car>Altima</car>
</garage>
So given the C# code:
XmlNode priusNode = GetReferenceToPriusNode()
What's the best way to cause the priusNode to "move up" one place in the garage's child list?
Get the previous sibling node, remove the node you want to move from its parent, and re-insert it before the sibling.
XmlNode parent = priusNode.ParentNode.
XmlNode previousNode = priusNode.PreviousSibling;
//parent.RemoveChild(priusNode); // see note below
parent.InsertBefore(priusNode, previousNode);
Error handling ignored but would be required for real implementation.
EDIT: Per Mike's comment, the RemoveChild call is superfluous: as the docs say, "If the newChild [in this case priusNode] is already in the tree, it is removed from its original position and added to its target position." Thanks Mike!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With