如何检查 XML 元素是否存在?

how to check if XML element exists or not?

我想扫描我的 xml 文件是否存在特定节点 这些是我的代码

 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

结果显示"Not Exists"。 在我注释掉我的 Try、Catch 和 End Try 之后,错误结果显示:

An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll

Additional information: 'RootName\PRODUCT\NAME' has an invalid token.

这是什么意思?

  1. 首先,路径不对。 / 是 xml 路径的路径分隔符,而不是 \
  2. 您不应在 xml 路径中指定 rootName,因为您已经为根节点 (xmlDoc.DocumentElement)
  3. 调用了 SelectSingleNode 函数
  4. 您识别不存在节点的方式不正确。 SelectSingleNode 如果路径不存在则不会抛出异常。相反,它只是 returns Nothing.

基于以上,修改代码如下:

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

要从根目录使用 SelectSingleNode,请使用以下路径:

xmlDoc.SelectSingleNode("descendant::PRODUCT/NAME")