Can't get the text from a node in XML
This is probably a simple question but using xmlhttp, how do I get the text of the token node in this XML? There has to be a better way than this:
XML.FirstChild.NextSibling.FirstChild.FirstChild.FirstChild.FirstChild.NextSibling.Text
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetToken2Response xmlns="webservice">
<GetToken2Result>
<ResponseStatus>
<ResponseCd>Fail or Success or Warning</ResponseCd>
<ResponseMsg>string</ResponseMsg>
<Version>string</Version>
</ResponseStatus>
<Token>st开发者_运维技巧ring</Token>
<Expiration>double</Expiration>
<Valid>boolean</Valid>
</GetToken2Result>
</GetToken2Response>
</soap:Body>
</soap:Envelope>
Updated to include namespaces. Unfortunately I can't figure out how to deal with the 'xmlns="webservice"' in your actual sample xml...
Sub Test()
Dim sXML As String
Dim xmlDoc As DOMDocument
Dim xNodeResult As IXMLDOMNode
Dim xNodeToken As IXMLDOMNode
Set xmlDoc = New DOMDocument40
sXML = "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""" & _
" xmlns:xsd = ""http://www.w3.org/2001/XMLSchema""" & _
" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">" & _
"<soap:Body>" & _
"<GetToken2Response>" & _
"<GetToken2Result>" & _
" <ResponseStatus>" & _
" <ResponseCd>Fail or Success or Warning</ResponseCd>" & _
" <ResponseMsg>string</ResponseMsg>" & _
" <Version>string</Version>" & _
" </ResponseStatus>" & _
" <Token>string</Token>" & _
" <Expiration>double</Expiration>" & _
" <Valid>boolean</Valid>" & _
"</GetToken2Result>" & _
"</GetToken2Response>" & _
"</soap:Body>" & _
"</soap:Envelope>"
xmlDoc.validateOnParse = True
xmlDoc.setProperty "SelectionNamespaces", _
"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"
xmlDoc.LoadXML (sXML)
If xmlDoc.parseError.reason <> "" Then
Debug.Print "Parse error: " & xmlDoc.parseError.reason
Exit Sub
End If
xmlDoc.setProperty "SelectionLanguage", "XPath"
Set xNodeResult = xmlDoc.DocumentElement.SelectSingleNode( _
"/soap:Envelope/soap:Body/GetToken2Response/GetToken2Result")
Debug.Print xNodeResult.XML
Set xNodeToken = xNodeResult.SelectSingleNode("Token")
If Not xNodeToken Is Nothing Then
Debug.Print xNodeToken.nodeTypedValue
Else
Debug.Print "???"
End If
End Sub
I saved your XML to a file, then ran this procedure and it gave me 'string' as the value for Token.
Public Sub ReadToken()
Dim strUrl As String
Dim objDoc As Object
Dim strToken As String
strUrl = CurrentProject.Path & Chr(92) & "brettville.xml"
Set objDoc = CreateObject("Msxml2.DOMDocument.3.0")
objDoc.async = False
objDoc.validateOnParse = True
objDoc.Load strUrl
strToken = objDoc.getElementsByTagName("Token").Item(0).Text
Debug.Print "strToken: '" & strToken & "'"
Set objDoc = Nothing
End Sub
精彩评论