Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to move "a child up" in a .NET XmlDocument?

Tags:

c#

xml

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?

like image 856
Mike Avatar asked Mar 13 '10 03:03

Mike


1 Answers

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!

like image 72
itowlson Avatar answered Sep 21 '22 22:09

itowlson