我想扫描我的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.
那是什么意思?
答案 0 :(得分:1)
/
是xml路径的路径分隔符,而不是\\
。rootName
,因为您已经为根节点(SelectSingleNode
)调用了xmlDoc.DocumentElement
函数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")