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 f开发者_JAVA技巧inal 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!
Try
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.parentnode.aspx
XmlNode nodParent = priusNode.ParentNode;
精彩评论