Building SOAP message with XMLDocument VB.NET

白昼怎懂夜的黑 提交于 2019-12-11 13:02:48

问题


I am having some problems building a properly formatted SOAP message using XMLDocument in VB.NET(C# answers are fine though).

I am using the following code to manually create my SOAP message, what is happening is that the namespace prefix of the soap:Header and soap:Body are being stripped in the output 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)

This results in the following output:

    <?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>

What I need is:

<?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>

NOTE: I appreciate all input, but regardless of any references to how SOAP should work or be parsed on the receiving side or anything like that, the bottom line is I need to generate the XML as described for. Thanks in advance!

SOLUTION: Very similar to Quartmeister answer was the way I resolved this. The issue was in fact in relation to namespace. Rather than use the string value every time though, I used the following solution using the NamespaceURI of the DocumentElement:

Dim soapHeader As XmlElement = _xmlRequest.CreateElement("soap", "Header", _xmlRequest.DocumentElement.NamespaceURI)
Dim soapBody As XmlElement = _xmlRequest.CreateElement("soap", "Body", _xmlRequest.DocumentElement.NamespaceURI)

回答1:


You need to set the XML namespace on the Header and Body elements to the soap namespace:

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/")


来源:https://stackoverflow.com/questions/3294251/building-soap-message-with-xmldocument-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!