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

时间:2019-08-29 09:18:28

标签: xml vb.net xmlnodelist

我想扫描我的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

结果显示“不存在”。 在我注释掉“尝试”,“捕获”和“结束尝试”之后,错误结果显示:

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

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

那是什么意思?

1 个答案:

答案 0 :(得分:1)

  1. 首先,路径不正确。 /是xml路径的路径分隔符,而不是\\
  2. 您不应在xml路径中指定rootName,因为您已经为根节点(SelectSingleNode)调用了xmlDoc.DocumentElement函数
  3. 您识别不存在节点的方式不正确。如果路径不存在,SelectSingleNode不会引发异常。相反,它仅返回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")