Tuesday, May 29, 2007

Adding Nodes using InnerText Property and CreateTextNode Method

In this blog, I'll discuss two simple ways of adding a node to an existing XML document.

Before we do anything, we will need to declare an XMLDocument and call the LoadXML method which takes an XML string as the parameter to populate the document

Dim objDocument As New System.Xml.XmlDocument
objDocument.LoadXML("<Cars></Cars")

Doing this, we will obtain a document with the root node as Cars and no child element.

In the first method, we will create the element using the CreateElement method, then create an XMLText object and set the value using CreateTextNode method, add the text object to the XML element before adding it to the document as follow:

Dim objElement As System.Xml.XmlElement
Dim objText As System.Xml.XmlText
objElement = objDocument.CreateElement("Make")
objText = objDocument.CreateTextNode("Honda")
objElement.AppendChild(objText)
objDocument.DocumentElement.AppendChild(objElement)

'these last too lines produce the same result as the previous two
'objDocument.DocumentElement.AppendChild(objElement)
'objDocument.DocumentElement.LastChild.AppendChild(objText)

The second method is much simpler. We create an element using the CreateElement method of the XMLElement object, set its value in the InnerText property and add it to the document using AppendChild method:

Dim objElement As System.Xml.XmlElement
objElement = objDocument.CreateElement("Make")
objElement.InnerText = "Toyota"
objDocument.DocumentElement.AppendChild(objElement)

There you have two ways of adding a new element to an existing XML document. I prefer the second method as it is much simpler, less coding and easier to understand.

TIPS: You can quickly show the content of the XML document by sending its content to a textbox using the following statement:

txtOutput.Text = objDocument.InnerXml

No comments: