TheCoder
TheCoder

Reputation: 191

Adding a node in the beginning of XML parent node

I wanted to add a xmlNode in a parent but at the top/beginning. Is there a variant of XMLNode.AppendChild() that i can use?

Upvotes: 3

Views: 7484

Answers (2)

Pouya Motakef
Pouya Motakef

Reputation: 51

I believe the question is asking how to add a node to the beginning of the XML file. I did that in the following manner:

// This is the main xml document
XmlDocument document = new XmlDocument();

// This part is creation of RootNode, however you want
XmlNode RootNode = document.CreateElement("Comments");
document.AppendChild(RootNode);

//Adding first child node as usual
XmlNode CommentNode1 = document.CreateElement("UserComment");
RootNode.AppendChild(commentNode1);

//Now create a child node and add it to the beginning of the XML file
XmlNode CommentNode2 = document.CreateElement("UserComment");
RootNode.InsertBefore(commentNode2, RootNode.FirstChild);

Upvotes: 0

croxy
croxy

Reputation: 4178

As far as I understand your question you are probably looking for the XmlNode.PrependChild() method.
Example:

XmlDocument doc = new XmlDocument();
XmlNode root = doc.DocumentElement;

//Create a new node.
XmlElement node = doc.CreateElement("price");

//Add the node to the document.
root.PrependChild(node);

MSDN documentation

Upvotes: 7

Related Questions