首页 > 解决方案 > 获取 id2 的值

问题描述

<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <id xmlns="id.services/">
         <ids1>
            <response xmlns="">
               <ids xmlns="ids">
                  <Id-info xmlns="" id0="123" id1="0" id2="2345" />
                  <Id-info xmlns="" id0="456" id1="1" id2="6789" />
               </ids>
            </response>
         </ids1>
      </id>
   </s:Body>
</s:Envelope>

如何使用 vba excel 获取 id2 的值?这是我尝试过的代码

Dim xmlDoc As DOMDocument30
Set xmlDoc = New DOMDocument30
xmlDoc.Load ("C:test.xml")

Dim id As String
id = xmlDoc.SelectSingleNode("//ids/Id-info").Attributes.getNamedItem("id2").Text

标签: excelvbaxml-parsing

解决方案


您将只能访问一个值。

尝试

Option Explicit

Public Sub test()
    Dim xmlDoc As Object, items As Object, node As IXMLDOMElement
    Set xmlDoc = CreateObject("MSXML2.DOMDocument") 'New MSXML2.DOMDocument60
    With xmlDoc
        .validateOnParse = True
        .setProperty "SelectionLanguage", "XPath"
        .async = False
        If Not .Load("C:\Users\User\Desktop\Test.xml") Then
            Err.Raise .parseError.ErrorCode, , .parseError.reason
        End If
    End With
    Set items = xmlDoc.SelectNodes("//Id-info")
    If Not items Is Nothing Then
        For Each node In items
            Debug.Print node.getAttribute("id2")
        Next
    End If
End Sub

推荐阅读