how to check if XML element exists or not?

3.7k Views Asked by At

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?

1

There are 1 best solutions below

4
ajakblackgoat On BEST ANSWER
  1. First of all, the path is incorrect. / is the path separator for xml path, not \\.
  2. You should not specify the rootName in the xml path since you already calling the SelectSingleNode function for the root node (xmlDoc.DocumentElement)
  3. The way you identify non-existence node incorrect. 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")