我正在尝试通过VBA从XML文件中获取某个节点。存在条件。如果节点“ Boolean.text” =“ false”,那么我需要具有节点“ Comment”的内容,但是,使用我使用的代码,我不断收到错误消息“运行时错误91,对象变量或未设置块变量” ”在线“ If(goodBad.hasChildNodes)然后”我无法弄清楚我在做什么错。我也有一种感觉,我正在为这种相当简单的请求使用复杂的代码。
希望有人可以给我一些指导。
Sub ReadXMLFile2()
Dim xDoc As New MSXML2.DOMDocument60
Dim strXMLFilePath As String
Dim list As IXMLDOMNodeList
Dim resp As IXMLDOMNode
Dim goodFalse As IXMLDOMNode
Dim goodBad As IXMLDOMNode
Dim reason As IXMLDOMNode
Dim textNodes As IXMLDOMNode
Dim node As IXMLDOMNode
Dim attr As IXMLDOMAttribute
Dim childNode As IXMLDOMNode
Dim strReason As String
Set xDoc = New MSXML2.DOMDocument60
strXMLFilePath = CurrentProject.Path & "\Test.xml"
With xDoc
.async = False
.validateOnParse = True
If Not xDoc.Load(strXMLFilePath) Then
Debug.Print .parseError.reason, .parseError.ErrorCode
End If
End With
Set list = xDoc.selectNodes("//ToBeCheckedResp/CheckResp/Resp")
For Each resp In list
Set attr = resp.Attributes.getNamedItem("status")
If (Not attr Is Nothing) Then
Debug.Print attr.Text
End If
If resp.hasChildNodes Then
For Each childNode In resp.childNodes
Set goodFalse = childNode.selectSingleNode("Boolean")
Debug.Print goodFalse.Text
Next childNode
End If
If goodFalse.Text = "true" Then
strReason = ""
ElseIf goodFalse.Text = "false" Then
If resp.hasChildNodes Then
Set goodBad = resp.selectSingleNode("False")
If (goodBad.hasChildNodes) Then
Set reason = goodBad.selectSingleNode("Why")
If reason.hasChildNodes Then
Set textNodes = reason.selectNodes("Comment")
For Each node In textNodes
strReason = strReason & " " & node.Text
Next node
End If
End If
End If
End If
Next resp
Set xDoc = Nothing
End Sub
使用的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<ToBeCheckedResp>
<CheckResp>
<Resp status="completed">
<Value>
<Boolean>true</Boolean>
<Good>
<Example>Test1</Example>
</Good>
</Value>
</Resp>
<Resp status="completed">
<Value>
<Boolean>false</Boolean>
<False>
<Why>
<Comment>Reason why boolean is false.</Comment>
</Why>
</False>
</Value>
</Resp>
</CheckResp>
</ToBeCheckedResp>
答案 0 :(得分:1)
Set goodBad = resp.selectSingleNode("False") If (goodBad.hasChildNodes) Then
错误91在这里意味着goodBad
是Nothing
,这意味着selectSingleNode
在False
下没有产生名为resp
的节点。
您似乎想要Value
节点;大概selectSingleNode
不会遍历子节点/后代以查找您给定的节点名称,而这个<Value>
节点就在这里。
因此,选择<Value>
节点,然后从那个节点选择selectSingleNode
。或者,使用做遍历子孙的另一种方法来查找特定节点。
无论哪种方式,都不应假定可以返回Nothing
的方法总是返回有效的对象引用。
如果可以在没有所需节点的情况下合理地恢复执行,那么您要防止Nothing
来防止针对无效对象引用进行非法成员调用:
Set goodBad = resp.selectSingleNode("False")
If Not goodBad Is Nothing Then
If (goodBad.hasChildNodes) Then
'...
End If
Else
'goodBad node doesn't exist. What now?
'...
End If
否则,您可以使用Debug.Assert
来使假设明确:
Set goodBad = resp.selectSingleNode("False")
Debug.Assert Not goodBad Is Nothing
If (goodBad.hasChildNodes) Then
如果未验证断言,那么执行将在那里暂停,您可以调试并继续。
关于复杂性,其根本原因是对节点层次结构进行了硬编码(resp
是goodBad
的父级,等等)并逐个遍历节点。您可以通过更精细的selectNodes
XPath查询来简化所有操作。