Best way to extend XmlDocument?

brendan.hill

Member
Joined
Jun 20, 2010
Messages
15
Programming Experience
10+
I would like to extend the functionality of XmlDocument and XmlElement to make it easier to add new children, multiple values at once, etc, for example this function would be useful:

VB.NET:
Public Function AddValues(paramarray NameThenValue() as object)
.
End Function

Dim x as XmlElement
.
.
x.AddValues("Name", "asdf", "Age", 13, "DateOfBirth", #1/1/1970#)

What's the best way to do this? Inheriting a class from XmlDocument/XmlElement is great except the inability to cast from base class to derived class (eg. XmlElement -> XmlElementEx) means that you can't properly wrap .AppendChild() and .SelectSingleNode().

I've since actually gone with a wrapper class (contains XmlElement as a private member, then exposes just my special functions) but it would be preferable to somehow extend the XmlElement class directly without loss of functionality.

Any suggestions?

-Brendan

P.S. Not interested in 3rd party products :(
 
Just apply the same logic you applied with the AddValues method, and create a proper constructor overload for the class. Instead of casting an object to it, pass the object through the class constructor.

Public Class XmlDocumentEx
    Inherits XmlDocument
    
    Public Overloads Sub New(ByVal objXmlDocument As XmlDocument)
        Me.LoadXml(objXmlDocument.OuterXml)
    End Sub
End Class
 
Just apply the same logic you applied with the AddValues method, and create a proper constructor overload for the class. Instead of casting an object to it, pass the object through the class constructor.

Public Class XmlDocumentEx
    Inherits XmlDocument
    
    Public Overloads Sub New(ByVal objXmlDocument As XmlDocument)
        Me.LoadXml(objXmlDocument.OuterXml)
    End Sub
End Class

Hmm the issue here is that repeated retrievals of child XmlElement nodes would result in the XML being serialized & deserialized on each request.
 
Back
Top