1

我试图在 VBA 中获取单个节点的属性,但无法使用 DOM 管理它

XML 如下所示:

    <?xml version="1.0" encoding="utf-8"?>
       <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap:Body>
             <GetUserInfoResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
                <GetUserInfoResult>
                   <GetUserInfo>
                      <User ID="16" Name="David" LoginName="login" Email="" Notes="" IsSiteAdmin="False" IsDomainGroup="False" />
                      <User ID="17" Name="Gal" LoginName="login" Email="" Notes="" IsSiteAdmin="False" IsDomainGroup="False" />
                      <User ID="18" Name="Netzer" LoginName="login" Email="" Notes="" IsSiteAdmin="False" IsDomainGroup="False" />
                      <User ID="3" Name="More" LoginName="login" Email="" Notes="" IsSiteAdmin="False" IsDomainGroup="False" />
                      <User ID="20" Name="Alon" LoginName="login" Email="" Notes="" IsSiteAdmin="False" IsDomainGroup="False" />
                      <User ID="21" Name="Dan" LoginName="login" Email="" Notes="" IsSiteAdmin="False" IsDomainGroup="False" />
                      <User ID="708" Name="Yaron" LoginName="login" Email="" Notes="" IsSiteAdmin="False" IsDomainGroup="False" />
                </GetUserInfo>
             </GetUserInfoResult>
          </GetUserInfoResponse>
       </soap:Body>
    </soap:Envelope>

我基本上只是想获取 ID 属性的值。任何帮助,将不胜感激。

这与以下链接中的问题相同: Read XML Attribute VBA with small change !正如您在 XML 文件中看到的那样,用户不止一个,因此以下答案不适合,

Try:

(Include a reference to Microsoft XML v3, I saved your xml to a file on my desktop)

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

    Dim id As String
    id = xmlDoc.SelectSingleNode("//GetUserInfo/User").Attributes.getNamedItem("ID").Text

我怎么知道他的ID是“21”的用户名?

如果有人能帮助我真的很高兴

4

1 回答 1

2

这对我有用:

Dim oDoc As New MSXML2.DOMDocument30
Dim el As Object
Dim XML As String

XML = ActiveSheet.Range("B1").Value 'for testing....

oDoc.validateOnParse = True
oDoc.LoadXML XML  '<< using LoadXML to load from a string
                  '   use Load if you're reading from a file

'select the User node with ID=21
Set el = oDoc.SelectSingleNode("//GetUserInfo/User[@ID=""21""]")

If Not el Is Nothing Then
    Debug.Print el.getAttribute("Name")
Else
    Debug.Print "user id not found!"
End If
于 2016-12-14T17:13:47.433 回答