如何从使用DataContractSerializer序列化的对象的XML表示中删除XML命名空间?
该对象需要序列化为一个非常简单的输出XML。
>最新&最大的 – 使用.Net 4 beta 2
>对象永远不需要反序列化。
> XML不应该有任何xmlns:…命名空间refs
>需要支持任何子类型的Exception和ISubObject。
>这将非常难以更改原始对象。
目的:
[Serializable] class MyObj { string str; Exception ex; ISubObject subobj; }
需要序列化成:
<xml> <str>...</str> <ex i:nil="true" /> <subobj i:type="Abc"> <AbcProp1>...</AbcProp1> <AbcProp2>...</AbcProp2> </subobj> </xml>
我使用这个代码:
private static string ObjectToXmlString(object obj) { if (obj == null) throw new ArgumentNullException("obj"); var serializer = new DataContractSerializer( obj.GetType(),null,Int32.MaxValue,false,new AllowAllContractResolver()); var sb = new StringBuilder(); using (var xw = XmlWriter.Create(sb,new XmlWriterSettings { OmitXmlDeclaration = true,NamespaceHandling = NamespaceHandling.OmitDuplicates,Indent = true })) { serializer.WriteObject(xw,obj); xw.Flush(); return sb.ToString(); } }
从this article我采用了一个DataContractResolver,所以没有子类型必须声明:
public class AllowAllContractResolver : DataContractResolver { public override bool TryResolveType(Type dataContractType,Type declaredType,DataContractResolver knownTypeResolver,out XmlDictionaryString typeName,out XmlDictionaryString typeNamespace) { if (!knownTypeResolver.TryResolveType(dataContractType,declaredType,out typeName,out typeNamespace)) { var dictionary = new XmlDictionary(); typeName = dictionary.Add(dataContractType.FullName); typeNamespace = dictionary.Add(dataContractType.Assembly.FullName); } return true; } public override Type ResolveName(string typeName,string typeNamespace,DataContractResolver knownTypeResolver) { return knownTypeResolver.ResolveName(typeName,typeNamespace,null) ?? Type.GetType(typeName + "," + typeNamespace); } }