Building an XML Document in Code
Question: How can I build an XML Document with Code for the Compact Framework? I understand that I can use the tools of Visual Studio, XML Spy or even Notepad to do this. Unfortunately, I don’t know the format of the actual XML Document until the application is running.
Answer: It is important to understand the Document Object Model (DOM) provides a set of classes that conforms to the World Wide Consortium (W3C) Level 1 Specification. It is these classes that we can use to both create and modify an XML Document in memory and navigate through the document. It is really the DOM that provides acess to the contents of the entire document. When the XML Parser (System.XML) in the .NET Compact Framework loads an XML Document into a DOM it creates a model of nodes from the schema and elements. The DOM has a node representing the root element that contains all the other elements of the document. For example, if we wanted to create an XML Document in code that contained the following the structure.
<customerList>
<name>Major Company</name>
</customerList>
We could use the following code that would create an XML Document when a Button is pressed.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xmlDoc As New XmlDocument
Dim xmlNode As XmlNode
xmlNode = xmlDoc.CreateElement("customerList")
xmlDoc.AppendChild(xmlNode)
xmlNode = xmlDoc.CreateElement("name")
xmlNode.InnerText = "Major Company"
xmlDoc.DocumentElement.AppendChild(xmlNode)
MsgBox(xmlDoc.OuterXml)
End Sub