XML: Why can't I create a parent node for my document?

  • Thread starter Thread starter Darrel
  • Start date Start date
D

Darrel

I'm trying to write an XML file. The first thing I want to do is create the
parent node for the document:

eleMenuItems = xmldoc.CreateElement("menuItems")
xmldoc.DocumentElement.PrependChild(eleMenuItems)

The second line above causes by try statement to exit and catches this
generic error:

'Object reference not set to an instance of an object'

I'm not sure where to do now to figure out the problem. Is there something I
am missing concept wise when creating the parent node?

-Darrel
 
You need to insert it as the document element before you dereference the document element - i.e.

XmlNode n = d.CreateElement("Foo");
d.InsertAfter(n, null);

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

I'm trying to write an XML file. The first thing I want to do is create the
parent node for the document:

eleMenuItems = xmldoc.CreateElement("menuItems")
xmldoc.DocumentElement.PrependChild(eleMenuItems)

The second line above causes by try statement to exit and catches this
generic error:

'Object reference not set to an instance of an object'

I'm not sure where to do now to figure out the problem. Is there something I
am missing concept wise when creating the parent node?

-Darrel
 
Thanks, Richard.

In the end, I scrapped this method and went with an XMLWriter one. Which I
got working.

Which raises the question, when should I use XMLWriters and when should I
use XMLDoc?

-Darrel
 
XmlWriter is part of the streaming API - in that once you have written something its gone. There is no going back to add bits in later. However, its very fast and efficient for writing out documents of which you have full knowledge of the structure when writing (rather than discovering the structure as the processing occurs, forcing you to adjust something you may already have written).

XmlDocument is far less efficient in terms of memory as it has to build an object model in memory before streaming the contents out (using the streaming API as it happens). Hoever, you have full flexibility to adjust the in memory model as processing occurs.

The third option is to use string concatenation via a StringBuilder which is the fastest way to construct an XML document - however, you then have to take full responsibility of getting the syntax correct and is arguable harder to understand and maintain.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog


Which raises the question, when should I use XMLWriters and when should I
use XMLDoc?
 
Back
Top