tags:

views:

73

answers:

2

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?

+3  A: 

Try

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.parentnode.aspx

XmlNode nodParent = priusNode.ParentNode;
RJ1516
can you explain more? How can I use ParentNode to alter the sequence of <garage>'s children?
Mike
+2  A: 

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!

itowlson
That is definitely straightforward and worked fine. I also noticed that the RemoveNode() call is extraneous - InsertBefore() will just move it.
Mike