Friday, March 9, 2007

Creating a new XMLNode instance in .Net

The .Net XMLNode can not be instantiated with new since it is an abstract class. To create a new one you have to create one of the more specific types like XMLElement or XMLAttribute. Unfortunately it doesn't look like you can just do New XMLElement either. You must use an XMLDocument and it's CreateElement method.

Here's a situation I had. I had a method that was taking in a value and a node. I wanted to assign that value to the node. Then I had the problem of the node not existing in certain circumstance. I wanted to create a new node and just give it a name and a value. I decided to pass in the parent of the node and then append it to the parent. I couldn't do that because it wouldn't know how to deal with that node without knowing if it is an element or an attribute or whatever. So I needed an element, but couldn't just do a New XMLElement either. I used the XMLDocument, excuted CreateElement and then passed that to the AppendChild method of the parent node. Note that the XMLDocument that you are attaching the Element to much be the same document that was used to create.

private Sub MyMethod(ByVal Value As String, ByVal n As XmlNode, ByVal ParentNode As XmlNode, doc as XMLdocument)

dim ele as XMLElement

If IsNothing(n) Then

ele = doc.CreateElement("MyName")
ele.InnerText= Value

End If

End Sub