I know this may seem like a silly question and I have attempted to check msdn documentation and also search this site for some time. I have unfortunately not been able to really understand how to do it.
I would like to insert a node after a second or third child. My XML's main content lies within its grandchildren and when I use root.insertafter I get it put right after very first child.
XML:
<myCourse>
<courseName>BEng Mobile and Web Computing</courseName>
<courseStructure>
<module>
<moduleTitle>Programming Methodology</moduleTitle>
<credits>15</credits>
<semester>1</semester>
</module>
<module>
<moduleTitle>Computer Systems Fundamentals</moduleTitle>
<credits>15</credits>
<semester>1</semester>
</module>
</courseStructure>
</myCourse>
And Code:
private void buttonCreateNode_Click(object sender, EventArgs e)
{
// Load the XML document.
XmlDocument document = new XmlDocument();
document.Load(@"temp.xml");
// Get the root element.
XmlElement root = document.DocumentElement;
// Create the new nodes.
XmlElement newModule = document.CreateElement("module");
XmlElement newTitle = document.CreateElement("moduleTitle");
XmlElement newCredits = document.CreateElement("credits");
XmlElement newSemester = document.CreateElement("semester");
XmlText title = document.CreateTextNode("ECA411");
XmlText credits = document.CreateTextNode("15");
XmlText semester = document.CreateTextNode("1");
// Insert the elements.
newBook.AppendChild(newTitle);
newBook.AppendChild(newCredits);
newBook.AppendChild(newSemester);
newTitle.AppendChild(title);
newCredits.AppendChild(credits);
newSemester.AppendChild(semester);
root.InsertAfter(newModule, root.LastChild);
document.Save(@"temp.xml");
Any help would be greatly appreciated.
Thanks for your help @Mikkelbu.
I have however found a solution to my problem in where to I am now able to accomplish what I was attempting to achieve.
As follows:
XmlNode parentNode = document.SelectSingleNode("myCourse/courseStructure/level4");
parentNode.InsertBefore(newModule, parentNode.FirstChild);