c# - 使用 XMLDocument VB.NET 构建 SOAP 消息

标签 c# xml vb.net soap xmldocument

我在 VB.NET 中使用 XMLDocument 构建格式正确的 SOAP 消息时遇到一些问题(尽管 C# 答案很好)。

我使用以下代码手动创建我的 SOAP 消息,发生的情况是 soap:Headersoap: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答案非常相似。这个问题实际上与命名空间有关。不过,我没有每次都使用字符串值,而是使用 DocumentElementNamespaceURI 来使用以下解决方案:

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

最佳答案

您需要将 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/")

关于c# - 使用 XMLDocument VB.NET 构建 SOAP 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3294251/

相关文章:

javascript - SAPUI5 通过属性名称从 XML 模型进行绑定(bind)聚合

asp.net - 使用 Azure ADFS 和 OWIN 进行 SSO

c# - 系统.Enum.GetValues : In C# not the same as in VB?

c# - 方法内联如何用于 C# 中的自动属性?

c# - 使用 asp.net c# 读取上传的 .csv 文件

c# - 迭代不同数据类型的列表?

c# - 为什么 >= 有效而 => 无效?

C# - 从 XML 文档中的特定标记获取值

xml - music21格式流为ABC+并保存为文件

vb.net - (OrElse 和 Or) 和 (AndAlso 和 And) - 何时使用?