I would like to scan my xml file whether the specific node is exists or not these are my codes
Dim xmlDoc As New XmlDocument()
xmlDoc.Load("C:\Users\Desktop\XMLFILE.xml")
Dim rootName As String = xmlDoc.DocumentElement.Name
Dim nodes As XmlNode
'Dim objTest As XmlElement
Try
nodes = xmlDoc.DocumentElement.SelectSingleNode(rootName & "\\PRODUCT\\NAME")
MessageBox.Show("Exists")
Catch ex As Exception
MessageBox.Show("Not exists")
End Try
The results shows "Not Exists". After I comment out my Try, Catch and End Try, the error results shows:
An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll
Additional information: 'RootName\\PRODUCT\\NAME' has an invalid token.
What does that mean?
/
is the path separator for xml path, not \\
.rootName
in the xml path since you already calling the SelectSingleNode
function for the root node (xmlDoc.DocumentElement
)SelectSingleNode
does not throw an exception if the path does not exist. Instead, it simply returns Nothing
.Based on the above, here are the modified code :
Dim xmlDoc As New XmlDocument()
xmlDoc.Load("C:\Users\Desktop\XMLFILE.xml")
Dim nodes As XmlNode
Try
nodes = xmlDoc.DocumentElement.SelectSingleNode("PRODUCT/NAME")
If nodes Is Nothing Then
MessageBox.Show("Not exists")
Else
MessageBox.Show("Exists")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
To use the SelectSingleNode
from the root, use the following path :
xmlDoc.SelectSingleNode("descendant::PRODUCT/NAME")