Andrew

Andrew

  • NA
  • 7
  • 0

How to insert XML child node programmatically

Mar 5 2009 11:26 AM

I have what seems to be a simple problem for which I can't find a simple answer. 

I have an XML file something like this:

<root>
 <firstLevel>
  <parent>
   <child>first child</child>
   <child>second child</child>
   <child>third child</child>
   <child>fourth child</child>
  </parent>
 </firstLevel>
</root>

I would like to write a small C# snippet that will allow me to insert a new child node as the first node in the parent (or maybe insert it at any point within the parent) so that I now have

<root>
 <firstLevel>
  <parent>
   <child>new child</child>
   <child>first child</child>
   <child>second child</child>
   <child>third child</child>
   <child>fourth child</child>
  </parent>
 </firstLevel>
</root>

I've tried using the .InsertBefore method of a node, but I keep getting an error with the second parameter (XmlNode refChild) that my reference is not a child of this node.

Thanks in advance.


Answers (7)