开发者

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

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜