How to read XML attributes using VBA to Excel?

后端 未结 2 446
青春惊慌失措
青春惊慌失措 2020-12-11 09:00

Here is my code..

    
   
       

        
2条回答
  •  天涯浪人
    2020-12-11 09:36

    Refer either to the element's .Text property or the .nodeTypeValue property :

    Sub TestXML()
    Dim xmlDoc As Object 'Or enable reference to Microsoft XML 6.0 and use: MSXML2.DOMDocument
    Dim elements As Object
    Dim el As Variant
    Dim xml$
    xml = ""
    xml = xml & ""
    xml = xml & "3"
    xml = xml & ""
    xml = xml & "FirstUser"
    xml = xml & "MySystem"
    xml = xml & ""
    
    Set xmlDoc = CreateObject("MSXML2.DOMDocument")
    '## Use the LoadXML method to load a known XML string
    xmlDoc.LoadXML xml
    '## OR use the Load method to load xml string from a file location:
    'xmlDoc.Load "C:\my_xml_filename.xml"
    
    '## Get the elements matching the tag:
    Set elements = xmlDoc.getElementsByTagName("DTS:Property")
    '## Iterate over the elements and print their Text property
    For Each el In elements
        Debug.Print el.Text
        '## Alternatively:
        'Debug.Print el.nodeTypeValue
    Next
    
    End Sub
    

    I know some value is 3 but what that value is how could I know??

    You can review the objects in the Locals window, and examine their properties:

    enter image description here

    Here is an alternative, which seems clunkier to me than using the GetElementsByTagName but if you need to traverse the document, you could use something like this:

    Sub TestXML2()
    Dim xmlDoc As MSXML2.DOMDocument
    Dim xmlNodes As MSXML2.IXMLDOMNodeList
    Dim xNode As MSXML2.IXMLDOMNode
    Dim cNode As MSXML2.IXMLDOMNode
    Dim el As Variant
    Dim xml$
    xml = ""
    xml = xml & ""
    xml = xml & "3"
    xml = xml & ""
    xml = xml & "FirstUser"
    xml = xml & "MySystem"
    xml = xml & ""
    
    Set xmlDoc = CreateObject("MSXML2.DOMDocument")
    '## Use the LoadXML method to load a known XML string
    xmlDoc.LoadXML xml
    '## OR use the Load method to load xml string from a file location:
    'xmlDoc.Load "C:\my_xml_filename.xml"
    
    '## Get the elements matching the tag:
    Set xmlNodes = xmlDoc.ChildNodes
    '## Iterate over the elements and print their Text property
    For Each xNode In xmlDoc.ChildNodes
        If xNode.NodeType = 1 Then  ' only look at type=NODE_ELEMENT
            For Each cNode In xNode.ChildNodes
                Debug.Print cNode.nodeTypedValue
                Debug.Print cNode.Text
            Next
        End If
    Next
    
    End Sub
    

提交回复
热议问题