在處理伺服器回傳的 XML 回應時,我們常需要檢視節點的結構、屬性與文字內容。下列 VBScript 函數 showallnode 可遞迴列印指定節點的完整資訊,方便除錯與資料驗證。
Function showallnode(rootname, myXMLDOC)
If rootname <> "" Then
Set nodeobj = myXMLDOC.documentElement.selectSingleNode("//" & rootname & "")
nodeAttributelen = nodeobj.attributes.length
returnstring = returnstring & "<BR>節點名稱:" & rootname
If nodeobj.text <> "" Then
returnstring = returnstring & "<BR>節點的文本:(" & nodeobj.text & ")"
End If
returnstring = returnstring & "<BR>{<BR>"
If nodeAttributelen <> 0 Then
returnstring = returnstring & "<BR>屬性數有 " & nodeAttributelen & " 個,分別是:"
End If
For i = 0 To nodeAttributelen - 1
returnstring = returnstring & "<li>" & nodeobj.attributes(i).Name & ": " & nodeobj.getAttribute(nodeobj.attributes(i).Name) & " </li>"
Next
If nodeobj.childNodes.Length <> 0 Then
If nodeobj.hasChildNodes() And LCase(nodeobj.childNodes.item(0).nodeName) <> "#text" Then
Set childnodeobj = nodeobj.childNodes
childnodelen = nodeobj.childNodes.Length
returnstring = returnstring & "<BR><BR>有 " & childnodelen & " 個子節點;<BR>分別是: "
For i = 0 To childnodelen - 1
returnstring = returnstring & "<li>" & childnodeobj.item(i).nodeName & "</li>"
Next
End If
End If
returnstring = returnstring & "<BR>}<BR>"
Response.Write returnstring
Set nodeobj = Nothing
End If
End Function
If XMLhttp.Status = 200 Then
Set xmlDOC = Server.CreateObject("MSXML.DOMDocument")
xmlDOC.load(xmlhttp.responseXML)
showallnode "LoginByAccountResponse", xmlDOC
Set xmlDOC = Nothing
Else
Response.Write XMLhttp.Status & " "
Response.Write XMLhttp.StatusText
End If
以下示範如何以 Msxml2.XMLHTTP 物件發送 application/x-www-form-urlencoded 格式的 POST 請求,並處理回應:
url = "https://s/"
SoapRequest = "username=" & username & "&password=" & passWord
Set xmlhttp = Server.CreateObject("Msxml2.XMLHTTP")
xmlhttp.Open "POST", url, False
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlhttp.setRequestHeader "HOST", " "
xmlhttp.setRequestHeader "Content-Length", LEN(SoapRequest)
xmlhttp.Send(SoapRequest)
Response.Write xmlhttp.Status & " "
Response.Write xmlhttp.StatusText
Set xmlhttp = Nothing
If xmlhttp.Status = 200 Then
Set xmlDOC = Server.CreateObject("MSXML.DOMDocument")
xmlDOC.load(xmlhttp.responseXML)
showallnode "string", xmlDOC
Set xmlDOC = Nothing
Else
Response.Write xmlhttp.Status & " "
Response.Write xmlhttp.StatusText
End If
重點提醒:請確認 Content-Type 與伺服器預期一致,並正確設定 Content-Length,避免因標頭不符導致 400 或 415 錯誤。