Navigating the XML Document
In this post I provided a simple example of how you can programmatically create an XML Document. Once created it can be saved directly to disk by adding the following line of code to end of the function
xmlDoc.Save("cust.xml")
It is important to remember that the XMLDocument is actually an in memory DOM tree. Once the XML source is loaded in the XMLDocument object you can navigate through the DOM and manipulate the data using the .NET Framework classes. The XMLNode provides various methods that can be used to navigate through the DOM Tree. Always remember that most nodes can have multiple child nodes of various types, such as Document, Document Fragment, Entity Reference, Element and Entity. Attributes are considered a property of the element node, and consists of a name/value pair. The following table lists some of the properties of the XMlNode class that can be used to navigate through the DOM and obtain the values of the Nodes.
Properties |
Description |
OuterXML |
Gets the markup representing this node and all of its children |
Value |
Gets or sets the value of the Node |
Attributes |
Gets the collection containing the attributes of the current node |
BaseURI |
Gets the base URI of the current node |
ChildNodes |
Gets all the children of the node |
FirstChild |
Gets the first child of the node |
NextSibling |
Gets the node immediately following the current node |
LastChild |
Gets the last child of the node |
InnerXML |
Gets or sets the markup representing only the child nodes of this node. |
innerText |
Gets or sets the concatenated values of the node or all its child nodes |
For example, if we had an XML file that contained the following data.
<customerList>
<name>Major Company</name>
</customerList>
We could use the following code in a button behind a form to read the saved XML file.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim xmldoc As New XmlDocument
xmldoc.Load("cust.xml")
Dim xmlNodes As XmlNodeList = xmldoc.DocumentElement.ChildNodes
Dim xmlstring As New StringBuilder
Dim custNode As XmlNode
For Each custNode In xmlNodes
Dim propNode As XmlNode
For Each propnode In custNode
xmlstring.Append(propnode.Name + ":" + propnode.InnerText)
MsgBox(xmlstring.ToString)
Next propNode
Next custNode
End Sub