How to parse XML using vba

前端 未结 8 1177
不思量自难忘°
不思量自难忘° 2020-11-22 08:46

I work in VBA, and want to parse a string eg



        
8条回答
  •  时光取名叫无心
    2020-11-22 09:19

    Update

    The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a beginners guide of the XML DOM.

    Public Sub LoadDocument()
        Dim xDoc As MSXML.DOMDocument
        Set xDoc = New MSXML.DOMDocument
        xDoc.validateOnParse = False
        If xDoc.Load("C:\My Documents\sample.xml") Then
            ' The document loaded successfully.
            ' Now do something intersting.
            DisplayNode xDoc.childNodes, 0
        Else
            ' The document failed to load.
            ' See the previous listing for error information.
        End If
    End Sub
    
    Public Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _
       ByVal Indent As Integer)
    
       Dim xNode As MSXML.IXMLDOMNode
       Indent = Indent + 2
    
       For Each xNode In Nodes
          If xNode.nodeType = NODE_TEXT Then
             Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _
                ":" & xNode.nodeValue
          End If
    
          If xNode.hasChildNodes Then
             DisplayNode xNode.childNodes, Indent
          End If
       Next xNode
    End Sub
    

    Nota Bene - This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) . Naturally using the XML facilities built into the VBA XML Dom would be much better. See the updates above.

    Original Response

    I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I've used basic string functions to access the xml data.

    This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.

    sample function

    
    openTag = ""
    closeTag = "" 
    
    ' Locate the position of the enclosing tags startPos = InStr(1, temp, openTag) endPos = InStr(1, temp, closeTag) startTagPos = InStr(startPos, temp, ">") + 1 ' Parse xml for returned value Data = Mid(temp, startTagPos, endPos - startTagPos)

提交回复
热议问题