我正在尝试通过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>