【问题标题】:Building SOAP message with XMLDocument VB.NET使用 XMLDocument VB.NET 构建 SOAP 消息
【发布时间】:2010-07-20 20:50:38
【问题描述】:

我在 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)

【问题讨论】:

    标签: c# xml vb.net soap xmldocument


    【解决方案1】:

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

    【讨论】:

    • @Quartmeister - +1 感谢您的回复。实际上,我刚刚使用 DocumentElement.NamespaceURI 解决了这个问题,这与您的答案基本相同。给你答案,因为它是正确的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2014-07-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    相关资源
    最近更新 更多