我试图使一些SOAP webServices正常运行,并且希望避免将XML创建为字符串,所以我试图使用MSXML2(在Excel VBA中)来生成它。但是,服务器要求名称空间以非常特定的方式出现:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://hostname/service">
<soapenv:Header/>
<soapenv:Body>
<v1:GetData>
<input1>value1</input1>
<input2>value2</input2>
</v1:GetData>
</soapenv:Body>
</soapenv:Envelope>
我想出了以下代码(部分取自http://www.vbforums.com/showthread.php?734859-RESOLVED-xml-namespace),使我与众不同:
Sub createXML()
Const soapNS As String = "http://schemas.xmlsoap.org/soap/envelope/"
Const bodyNS As String = "http://hostname/service"
Dim XmlDom As MSXML2.DOMDocument60
Dim Node As MSXML2.IXMLDOMElement
Dim Attr As MSXML2.IXMLDOMAttribute
Set XmlDom = New MSXML2.DOMDocument60
With XmlDom
Set Node = .createNode(NODE_ELEMENT, "soapenv:Envelope", soapNS)
.appendChild Node
Set Attr = .createNode(NODE_ATTRIBUTE, "xmlns:v1", bodyNS)
Attr.NodeValue = bodyNS
Node.setAttributeNode Attr
Set Attr = Nothing
With Node
Set Node = XmlDom.createNode(NODE_ELEMENT, "soapenv:Header", soapNS)
.appendChild Node
Set Node = XmlDom.createNode(NODE_ELEMENT, "soapenv:Body", soapNS)
.appendChild Node
With Node
Set Node = XmlDom.createNode(NODE_ELEMENT, "v1:GetData", bodyNS)
.appendChild Node
With Node
Set Node = XmlDom.createNode(NODE_ELEMENT, "v1:input1", bodyNS)
.appendChild Node
Node.appendChild XmlDom.createTextNode("value1")
Set Node = XmlDom.createNode(NODE_ELEMENT, "v1:input2", bodyNS)
.appendChild Node
Node.appendChild XmlDom.createTextNode("value2")
End With
End With
End With
End With
End Sub
产生以下XML:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://hostname/service">
<soapenv:Header/>
<soapenv:Body>
<v1:GetData>
<v1:input1>value1</v1:input1>
<v1:input2>value2</v1:input2>
</v1:GetData>
</soapenv:Body>
</soapenv:Envelope>
但是,服务器不喜欢任何“ GetData”子项前面的“ v1”前缀。
如果我从createNode行中删除前缀:
Set Node = XmlDom.createNode(NODE_ELEMENT, "v1:input1", bodyNS)
到
Set Node = XmlDom.createNode(NODE_ELEMENT, "input1", bodyNS)
它会产生以下内容,服务器也不喜欢:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://hostname/service">
<soapenv:Header/>
<soapenv:Body>
<v1:GetData>
<input1 xmlns="http://hostname/service">value1</input1>
<input2 xmlns="http://hostname/service">value2</input2>
</v1:GetData>
</soapenv:Body>
</soapenv:Envelope>
关于如何在不使用字符串手动构建XML的情况下实现服务器所需的特定格式的任何想法?
编辑:这似乎是解决方案的la脚,但它可以工作。我宁愿不需要几个字符串替换的解决方案:
xmlStr = Replace(Replace(xmlStr, " xmlns=""http://hostname/service""", ""), "GetData", "v1:GetData")