public static string GetXMLFromObject(object obj){ XmlSerializer xs = new XmlSerializer(obj.GetType()); // Set up chain of writers StringBuilder sb = new StringBuilder(); using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(sb))) { writer.Formatting = Formatting.Indented; // Remove standard namespace attributes XmlSerializerNamespaces xsn = new XmlSerializerNamespaces(); xsn.Add(string.Empty, string.Empty); xs.Serialize(writer, obj, xsn); } return sb.ToString();}
public static string GetXMLFromObject(object obj)
{
XmlSerializer xs = new XmlSerializer(obj.GetType());
// Set up chain of writers
StringBuilder sb = new StringBuilder();
using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(sb)))
writer.Formatting = Formatting.Indented;
// Remove standard namespace attributes
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add(string.Empty, string.Empty);
xs.Serialize(writer, obj, xsn);
}
return sb.ToString();
The key is to create an XmlSerializerNameSpaces object, populate it with empty strings, and then pass it to the XmlSerizliazer. The result is a more compact XML file. Note that this works, despite the comment in the documentation explicitly saying that it isn't supported.
You can also use this class to add your own custom namespaces. This could be useful to prefix certain elements with a certain namespace.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.