What is the best way to move a child up in a .NET XmlDocument?

For 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 that it appears above the Altima node. Here is the final structure I want:

 <garage> <car>Firebird</car> <car>Prius</car> <car>Altima</car> </garage> 

So, with C # code:

 XmlNode priusNode = GetReferenceToPriusNode() 

What is the best way to make priusNode "move" one place in the list of children of the garage?

+4
source share
2 answers

Get the previous sibling node, remove the node you want to move from your parent, and paste it in front of the sibling.

 XmlNode parent = priusNode.ParentNode. XmlNode previousNode = priusNode.PreviousSibling; //parent.RemoveChild(priusNode); // see note below parent.InsertBefore(priusNode, previousNode); 

Error handling is ignored, but will be necessary for real implementation.

EDIT: Mike comment, calling RemoveChild is superfluous: as the docs say: "If newChild [in this case, priusNode] is already in the tree, it is removed from its original position and added to its target position." Thanks to Mike!

+8
source
-1
source

Source: https://habr.com/ru/post/1303997/


All Articles