Note that there are some explanatory texts on larger screens.

plurals
  1. POSerializing object with no namespaces using DataContractSerializer
    text
    copied!<p>How do I remove XML namespaces from an object's XML representation serialized using DataContractSerializer?</p> <p>That object needs to be serialized to a very simple output XML.</p> <ul> <li>Latest &amp; greatest - using .Net 4 beta 2</li> <li>The object will never need to be deserialized.</li> <li>XML should not have any xmlns:... namespace refs</li> <li>Any subtypes of Exception and ISubObject need to be supported.</li> <li>It will be very difficult to change the original object.</li> </ul> <p>Object:</p> <pre><code> [Serializable] class MyObj { string str; Exception ex; ISubObject subobj; } </code></pre> <p>Need to serialize into:</p> <pre><code>&lt;xml&gt; &lt;str&gt;...&lt;/str&gt; &lt;ex i:nil="true" /&gt; &lt;subobj i:type="Abc"&gt; &lt;AbcProp1&gt;...&lt;/AbcProp1&gt; &lt;AbcProp2&gt;...&lt;/AbcProp2&gt; &lt;/subobj&gt; &lt;/xml&gt; </code></pre> <p>I used this code:</p> <pre><code>private static string ObjectToXmlString(object obj) { if (obj == null) throw new ArgumentNullException("obj"); var serializer = new DataContractSerializer( obj.GetType(), null, Int32.MaxValue, false, false, null, 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(); } } </code></pre> <p>From <a href="http://blogs.msdn.com/youssefm/archive/2009/06/05/introducing-a-new-datacontractserializer-feature-the-datacontractresolver.aspx" rel="noreferrer">this article</a> I adopted a DataContractResolver so that no subtypes have to be declared:</p> <pre><code>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, null, 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, Type declaredType, DataContractResolver knownTypeResolver) { return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null) ?? Type.GetType(typeName + ", " + typeNamespace); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload