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

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
 
R

Richard Blewett [DevelopMentor]

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
 
D

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
 
R

Richard Blewett [DevelopMentor]

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top