How to Check for Null If an XML Node Exists in VB
Extensible markup language (XML) is a set of rules that enables a document to store data in a hierarchical fashion. An XML document is made up of several nodes connected in a tree data structure. A tree data structure has one root node and one or more child nodes. Each child node can have zero or more child nodes themselves. When parsing an XML file using a language like Visual Basic (VB), you must test to see if a child node exists. You can do this by testing to see if the value of the node is null, which means it doesn't exist. Visual Basic uses the Nothing keyword to test for null values.
Instructions
-
-
1
Launch Visual Studio by clicking on its icon. After it loads, select "File," then "New," and finally "Project." A "New Project" window opens.
-
2
Select "Visual Basic" from the left-hand column and "Console Application" from the right-hand column in the "New Project" window. Enter a name for the project and press the "Enter" key to create a new project. The main editor window loads a Visual Basic source code file, which contains a "main" subroutine.
-
-
3
Look at the main subroutine. It has two parts: a beginning and an end. All of the code in the following steps belongs right between these two parts. The two parts of the main subroutine look like this:
Sub Main()
End Sub
-
4
Write the following statement to create a new "XMLDocument" variable named "doc" as follows:
Dim doc As New XmlDocument()
-
5
Create a short XML document that consists of a root node and a child node that describe a customer. The root node will be "customer" and the child node will be "customerName." Use the "LoadXml" function to create the XML file right inside the source code:
doc.LoadXml("<customer>" & _
"<customerName>Peter</customerName>" & _
"</customer>")
-
6
Write a statement that creates a list of all of the child nodes from the "doc" XML variable like this:
Dim nodes As XmlNodeList = doc.ChildNodes
-
7
Write a statement that traverses the list of child nodes like this:
For Each node In nodes
-
8
Check if the current node in the list of nodes is null. If the value is null, write a message that says "Null node." In Visual Basic, check for null by checking to see if it is "Nothing," like this:
If (node Is Nothing) Then
Console.WriteLine("Null node")
Else
Console.WriteLine("Not Null")
End If
-
9
Continue through the "For Each" statement, so that you can test every child node in the XML file. Write the following line to conclude your program:
Next
-
10
Execute your program by pressing the green "Play" button, located near the top of the Visual Studio IDE. Since the XML document has one child node, the output of the program looks like this:
"Not Null"
-
1