Fri 4 Nov 2005
Avoid passing .NET XmlDocument objects to methods
Posted by andy under Programming
No Comments
I have decided that when using the .NET framework’s XML classes it is a bad idea to pass XmlDocument objects to methods. It is a much better idea to pass the document’s root XmlNode object instead.
The reason for this is that at some point down the line you might, as I have today, decide that you need to use one of your methods on a sub-set of a document. If your methods are setup to receive XmlDocument objects then you suddenly have a lot of code to refactor to allow you to pass an XmlNode object from an arbitary level in the document instead.
…insert useful example here…
Passing the XmlNode object is just as easy as passing the document and you can still access the document via the XmlNode.OwnerDocument property anyway.
Update:
I discovered a serious problem with this approach today. The XmlNode object that represents the top level of the XmlDocument returns null from its OwnerDocument property! Doh!
How annoying is that? I can see how logically the node that represents the document itself doesn’t really have an owner document. However it seems a very pureist way of looking at it and it isn’t a very useful design decision for someone using the class.
So all the methods on which I carefully replaced the XmlDocument parameters with XmlNode parameters have now had to gain an XmlDocument parameter as well, otherwise there is no way to insert new nodes and elements.