Groups | Blog | Home
all groups > dotnet xml > july 2003 >

dotnet xml : XmlDocument: I keep getting told "The reference node is not a child of this node"


George W.
7/18/2003 6:18:07 PM
Okay, I'm a C#/XML newbie, and I've been wrestling with this for a while
now, checked dotnet sites, articles, MSDN Library, etc. and haven't been
able to determine why this is happening.

I have an xml file that I am loading into an XmlDocument and then trying
to add a child element to the root element. I keep getting:
System.ArgumentException: The reference node is not a child of this node.

This occurs at the line where I'm using XmlDocument.InsertBefore.

Here's my code:

----CODE----
// Instantiate XmlDocument and load the file into it
XmlDocument doc = new XmlDocument();
doc.Load("/inetpub/wwwroot/xmlfun/news.xml");

// bookmark the root element
XmlNode root = doc.DocumentElement;

// set up my child element I want to insert
XmlElement elem = doc.CreateElement("news");
elem.InnerText = EnterNewsBox.Text;
elem.SetAttribute("date", DateTime.Now.ToLongDateString());
elem.SetAttribute("time", DateTime.Now.ToLongTimeString());
elem.SetAttribute("poster", PosterBox.Text);

// The exception occurs here:
doc.InsertBefore(elem, root.FirstChild);

doc.Save("/inetpub/wwwroot/xmlfun/news.xml");
------------


----"news.xml"----
<?xml version="1.0"?>
<updates>
<news date="Friday, July 18, 2003" time="8:00:37 AM">text is here</news>
</updates>
------------------

I want my child element, elem, to go about the current "news" element
that is there, so the output will be:

----"news.xml"----
<?xml version="1.0"?>
<updates>
<news date="Current dateblahblah" time="12:00:00 AM" poster="Bill">text
is here</news>
<news date="Friday, July 18, 2003" time="8:00:37 AM">text is here</news>
</updates>
------------------
Kirk Allen Evans
7/19/2003 4:26:16 PM
Change it to:


root.InsertBefore(elem, root.FirstChild);


--
Kirk Allen Evans
www.xmlandasp.net
Read my web log at http://weblogs.asp.net/kaevans


[quoted text, click to view]

AddThis Social Bookmark Button