我在使用 DataContractSerializer 时看到了一些异常行为。我已经定义了一个消息契约,如下所示:
namespace MyNamespace.DataContracts
{
[MessageContract(WrapperName = "order", WrapperNamespace = @"http://example.com/v1/order")]
public class MyOrder
{
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 1)]
public MyStore store;
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 2)]
public MyOrderHeader orderHeader;
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 3)]
public List<MyPayment> payments;
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 4)]
public List<MyShipment> shipments;
}
.
.
我正在向它发送一条如下所示的 XML 消息:
<?xml version="1.0" encoding="utf-8"?>
<order xmlns="http://example.com/v1/order>
<store>
...
</store>
<orderHeader>
...
</orderHeader>
<payments>
<payment>
...
</payment>
</payments>
<shipments>
<shipment>
...
</shipment>
</shipments>
</order>
我的服务按预期反序列化此 XML。在我的服务中,我使用 DataContractSerializer 创建一个 XML 字符串,这就是事情变得奇怪的地方。我正在使用这样的序列化程序:
DataContractSerializer serializer = new DataContractSerializer(typeof(MyOrder));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, order);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string outputMessage = sr.ReadToEnd();
}
完成后,outputMessage 将包含以下 XML:
<?xml version="1.0" encoding="utf-8"?>
<MyOrder xmlns="http://example.com/v1/order" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<order>
<store>
...
</store>
<orderHeader>
...
</orderHeader>
<payments>
<payment>
...
</payment>
</payments>
<shipments>
<shipment>
...
</shipment>
</shipments>
</order>
</MyOrder>
不用说,任何期望接收原始 XML 消息的东西都无法解析它。所以我想我有两个问题:
- 为什么 DataContractSerializer 将额外的外部节点添加到我的 XML 输出中?
- 有没有办法阻止它这样做?
谢谢。
我可能应该添加这是.NET 4。