我在使用VB.NET中的 XMLDocument 构建格式正确的 SOAP 消息时遇到了一些问题(虽然C#答案很好)。
我使用以下代码手动创建 SOAP 消息,发生的事情是 soap:Header 和 soap:Body的命名空间前缀正在输出XML中被删除:
Dim soapEnvelope As XmlElement = _xmlRequest.CreateElement("soap", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/")
soapEnvelope.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
soapEnvelope.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
_xmlRequest.AppendChild(soapEnvelope)
Dim soapHeader As XmlElement = _xmlRequest.CreateElement("soap", "Header", String.Empty)
_xmlRequest.DocumentElement.AppendChild(soapHeader)
Dim soapBody As XmlElement = _xmlRequest.CreateElement("soap", "Body", String.Empty)
_xmlRequest.DocumentElement.AppendChild(soapBody)
这导致以下输出:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Header>
...
</Header>
<Body>
....
</Body>
</soap:Envelope>
我需要的是:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Header>
...
</soap:Header>
<soap:Body>
....
</soap:Body>
</soap:Envelope>
注意:我感谢所有输入,但无论是否有任何关于 SOAP 应该如何工作或在接收方或其他类似方面进行解析的参考,底线是我需要按照描述生成XML。提前谢谢!
解: 与 Quartmeister 非常相似的答案就是我解决这个问题的方式。问题实际上与命名空间有关。不是每次都使用字符串值,而是使用以下解决方案,使用 DocumentElement 的 NamespaceURI :
Dim soapHeader As XmlElement = _xmlRequest.CreateElement("soap", "Header", _xmlRequest.DocumentElement.NamespaceURI)
Dim soapBody As XmlElement = _xmlRequest.CreateElement("soap", "Body", _xmlRequest.DocumentElement.NamespaceURI)
答案 0 :(得分:2)
您需要将Header和Body元素上的XML命名空间设置为soap命名空间:
Dim soapHeader As XmlElement = _xmlRequest.CreateElement("soap", "Header", "http://schemas.xmlsoap.org/soap/envelope/")
Dim soapBody As XmlElement = _xmlRequest.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/")