all groups > dotnet xml > september 2005 >
You're in the

dotnet xml

group:

XmlDocument



XmlDocument Andrew Robinson
9/26/2005 2:19:30 PM
dotnet xml: I am attempting to create an XmlDocument object but keep getting "Object
reference not set to an instance of an object" exceptions when I try to add
elements or attributes.

I don't have an existing document to load but want to create one from
scratch. How can I do this?

Just a simple example. I am sure I am missing something obvious to everyone
but me..

Thanks,

Re: XmlDocument Derek Harmon
9/26/2005 7:34:54 PM
[quoted text, click to view]

One of the reasons is so XmlDocument can set itself as the owner of the
XmlNode (why I need to use ImportNode( ) to move an XmlNode out
of one document and into another).

It seems subtle, but this factory pattern allow DOM implementations to
make some optimizations in how it keeps tabs on the XmlNodes that
may one day be joined to it. I'd expect, after all, if I created an Xml-
Element from an XmlDocument that I'm going to AppendChild it to the
same document soon, rather than import it to another XmlDocument to
append it there. I don't believe .NET's XmlDocument makes any opti-
mization of this sort, but it would be possible. Besides, if there were a
public constructor, everyone would be running around with orphan nodes.

Also, XmlNode in particular is an abstract base type, so an XmlNode
by itself or even a subclass of an XmlNode that isn't one of the pre-
determined types wouldn't fit into the XML Infoset.

[quoted text, click to view]

The factory methods don't add the XmlNode into the XmlDocument
themselves because it'd require a lot of additional information (where:
before, after, or as a child of; and in relation to what context node).
Sometimes this could be a convenience, since as I've said, we're
usually going to add the XmlNode to the same XmlDocument we've
just created it off of. There are still times when I might want to defer
appending the nodes, though. For example, when recursing depth first
over some object graph to build an XmlDocument from the leaf nodes
up.


Derek Harmon

Re: XmlDocument Pascal Schmitt
9/26/2005 11:36:42 PM
Hello!

Always remember: if you have some code that throws an exception - post it!

Here's an example:

// create document
XmlDocument d = new XmlDocument();

// create root node
XmlElement root = d.CreateElement("root");

// add to document
d.AppendChild( root );

// add element to root node
root.AppendChild( d.CreateElement("foo") );

// set an attribute
root.SetAttribute("bar", "foo");


For some reason you can't create XmlNode-s (XmlNode, XmlElement,
XmlAttribute...) by their constructors - you have to use the
CreateXXX-Methods provided by your XmlDocument - they will return the
object you wish to create but /not/ add it to the XML-tree, you have to
do it yourself (for example using AppendChild)


--
AddThis Social Bookmark Button