使用DataContractSerializer时,我无法获取xml输出以匹配C#合同。
以下是相互嵌套的具有不同名称空间的示例类。
[DataContract(Name = "TestClass", Namespace = "http://testclass.com")]
public class TestClass
{
[DataMember]
public PropertyOne PropertyOne { get; set; }
[DataMember]
public PropertyTwo PropertyTwo { get; set; }
}
[DataContract(Name = "PropertyOne", Namespace = "http://propertyone.com")]
public class PropertyOne
{
[DataMember]
public ExtendedPropertyOne ExtendedPropertyOne { get; set; }
}
[DataContract(Name = "PropertyTwo", Namespace = "http://propertytwo.com")]
public class PropertyTwo
{
[DataMember]
public ExtendedPropertyTwo ExtendedPropertyTwo { get; set; }
}
[DataContract(Name = "ExtendedPropertyOne", Namespace = "http://propertyone.com")]
public class ExtendedPropertyOne
{
}
[DataContract(Name = "ExtendedPropertyTwo", Namespace = "http://propertytwo.com")]
public class ExtendedPropertyTwo
{
}
然后设置对象:
var testclass = new TestClass()
{
PropertyOne = new PropertyOne { ExtendedPropertyOne = new ExtendedPropertyOne() },
PropertyTwo = new PropertyTwo { ExtendedPropertyTwo = new ExtendedPropertyTwo() }
};
我使用DataContractSerializer如下:
public static string SerializeAsXml<T>(T data)
{
var sb = new StringBuilder();
var xmlSettings = new XmlWriterSettings()
{
OmitXmlDeclaration = true,
Indent = true
};
using (var xw = XmlWriter.Create(sb, xmlSettings))
{
new DataContractSerializer(typeof(T)).WriteObject(xw, data);
}
return sb.ToString();
}
我得到以下输出,请注意,当C#协定分别在propertyone和propertytwo命名空间中指定默认名称空间时,在默认名称空间testclass.com中定义了PropertyOne和PropertyTwo元素。
<TestClass xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://testclass.com">
<PropertyOne xmlns:d2p1="http://propertyone.com">
<d2p1:ExtendedPropertyOne />
</PropertyOne>
<PropertyTwo xmlns:d2p1="http://propertytwo.com">
<d2p1:ExtendedPropertyTwo />
</PropertyTwo>
</TestClass>
预期输出为:
<TestClass xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://testclass.com">
<d2p1:PropertyOne xmlns:d2p1="http://propertyone.com">
<d2p1:ExtendedPropertyOne />
</d2p1:PropertyOne>
<d2p2:PropertyTwo xmlns:d2p2="http://propertytwo.com">
<d2p2:ExtendedPropertyTwo />
</d2p2:PropertyTwo>
</TestClass>
在正确的名称空间中使用PropertyOne和PropertyTwo类。
这会导致合同验证出现问题,这是错误还是已知限制?