我很擅长使用VBA阅读XML响应(请原谅我的无知)。有几个帖子可以解释它,但我无法在我的回复中复制它。我想获得标题" H1"和 requiredID " 22"。任何想法,我哪里出错?
以下是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>
<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<GetListItemsResult>
<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
<rs:data ItemCount="1">
<z:row Title="H1"
RequiredID="22"/>
</rs:data>
</listitems>
</GetListItemsResult>
</GetListItemsResponse>
</soap:Body>
</soap:Envelope>
以下是VBA脚本:
Sub GetXML_Values()
Dim listNode As MSXML2.IXMLDOMNode
Dim XMLDOC As MSXML2.DOMDocument
Set XMLDOC = New MSXML2.DOMDocument
XMLDOC.async = False
XMLDOC.Load ("File Location")
XMLDOC.setProperty "SelectionLanguage", "XPath"
XMLDOC.setProperty "SelectionNamespaces", "xmlns:sp=""http://schemas.microsoft.com/sharepoint/soap/"""
Set lists = XMLDOC.SelectNodes("//soap:Envelope/soap:Body/sp:GetListItemsResponse/sp:GetListItemsResult/sp:listitems/sp:data")
txt = XMLDOC.SelectSingleNode("//data/row").Attributes.getNamedItem("Title").Text
txt = XMLDOC.getElementsByTagName("soap:Envelope")(0).Text
For Each listNode In lists
Text = listNode.ChildNodes(0).Text
Next
Set XMLDOC = Nothing
End Sub
答案 0 :(得分:1)
基本上,您的挑战是XML响应中的多个名称空间,其中一个是没有任何前缀的默认名称空间。考虑在 SelectionNamespaces 属性中定义所有需要的命名空间,然后在XPath中向下走每个节点,相应地指定每个前缀。任何没有定义前缀的节点都将使用映射到sp
的默认命名空间。
下面将使用@Title
在立即窗口(Ctrl + G)中以标量和循环格式打印相同的@RequiredID
和Debug.Print
值:
Sub GetXML_Values()
Dim listNode As MSXML2.IXMLDOMNode, lists As MSXML2.IXMLDOMNodeList
Dim txt As String, Text As String
Dim i As Integer
Dim XMLDOC As MSXML2.DOMDocument
Set XMLDOC = New MSXML2.DOMDocument
XMLDOC.async = False
XMLDOC.Load ("G:\Sandbox\TitledRequiredXPath.xml")
XMLDOC.setProperty "SelectionLanguage", "XPath"
XMLDOC.setProperty "SelectionNamespaces", "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' " & _
"xmlns:sp='http://schemas.microsoft.com/sharepoint/soap/' " & _
"xmlns:rs='urn:schemas-microsoft-com:rowset' " & _
"xmlns:z='#RowsetSchema'"
Set lists = XMLDOC.SelectNodes("//soap:Envelope/soap:Body/sp:GetListItemsResponse/sp:GetListItemsResult/sp:listitems/rs:data")
txt = XMLDOC.SelectSingleNode("//rs:data/z:row").Attributes.getNamedItem("Title").Text
Debug.Print txt
txt = XMLDOC.SelectSingleNode("//rs:data/z:row").Attributes.getNamedItem("RequiredID").Text
Debug.Print txt
For Each listNode In lists
For i = 0 To listNode.ChildNodes(0).Attributes.Length - 1
Debug.Print listNode.ChildNodes(0).Attributes(i).Text
Next i
Next listNode
Set lists = Nothing
Set XMLDOC = Nothing
End Sub
<强>输出强>
H1
22
H1
22