我已经大大缩短了这个问题,因为到目前为止我还没有得到任何答案。
基本上我正在尝试使用DataContractSerializer序列化接口。但是当使用DataContractResolver执行此操作时,生成的XML实际上非常详细。我有一个接口IAnimal和一个具体的实现Cat。
如果我只是序列化Cat,我会得到XML:
<Cat xmlns="http://schemas.datacontract.org/2004/07/TestDataContractResolver.Concrete" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Species>feline</Species>
<Weight>1</Weight>
</Cat>
但是,在DataContractResolver的帮助下序列化IAnimal时,我得到以下XML:
<z:anyType i:type="a:TestDataContractResolver.Concrete.Cat" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:a="TestDataContractResolver.Concrete, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<Species xmlns="http://schemas.datacontract.org/2004/07/TestDataContractResolver.Concrete">feline</Species>
<Weight xmlns="http://schemas.datacontract.org/2004/07/TestDataContractResolver.Concrete">1</Weight>
</z:anyType>
这是冗长冗长的。为什么它会将xmlns粘贴到每个属性元素中,而不仅仅是根元素?我怎么能不这样做呢?
顺便说一句,这是基于Youssef Moussaoui's blog的DataContractSerializer的实现:
public class ModelDataContractResolver : DataContractResolver
{
public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
{
return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null) ?? Type.GetType(typeName + ", " + typeNamespace);
}
public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
if (knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace))
{
return true;
}
XmlDictionary dictionary = new XmlDictionary();
typeName = dictionary.Add(type.FullName);
typeNamespace = dictionary.Add(type.Assembly.FullName);
return true;
}
}