由 XMLWriter 在 WCF 自定义编码器中生成的 XML,生成命名空间冲突

本文关键字:XML 冲突 命名空间 XMLWriter WCF 自定义 编码器 | 更新日期: 2023-09-27 18:32:29

我正在 WCF 应用程序中使用自定义编码器来写出 SOAP 消息 XML。当我使用内置于 WCF 中的默认 XML textMessageEncoding时,这很好,但是当我使用自定义编码器时,命名空间出现问题 - 下面的 xmlns:a 标记(在元素和元素中(为两个不同的命名空间定义了两次,这在解析时会导致服务端出现问题

<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action a:mustUnderstand="1" u:Id="_3" xmlns="http://www.w3.org/2005/08/addressing" **xmlns:a="http://schemas.xmlsoap.org/soap/envelope/"**></Action>
    <MessageID u:Id="_4" xmlns="http://www.w3.org/2005/08/addressing">
      <!--Omitted-->
    </MessageID>
    <ActivityId CorrelationId="1" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">
      <!--Omitted-->
    </ActivityId>

关于如何解决此问题的任何想法?我正在使用自定义编码器中的 C# XmlWriter来编写 XML,这似乎是导致问题的原因。

另外,我如何让XmlWriter为上面的 <Action> 标签使用前缀,以便对其进行<a:Action>,而不是为每个声明使用 xmlns -

<Action a:mustUnderstand="1" u:Id="_3" xmlns="http://www.w3.org/2005/08/addressing"

这是我的 XmlWriterSettings

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Encoding = Encoding.GetEncoding(factory.CharSet);
writerSettings.OmitXmlDeclaration = true;
writerSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates;  

由 XMLWriter 在 WCF 自定义编码器中生成的 XML,生成命名空间冲突

通过使用

XmlDictionaryWriter而不是XmlWriter来解决此问题。幸运的是,我使用的是 Utf-8 编码,并且可以选择这样做