I want a way to serialise generic objects into XML fragments.
The fragments will be inserted into other XML documents and as such, I require a result that would look something like:
<firstProperty>firstPropertyValue</firstProperty>
<secondProperty>secondPropertyValue</secondProperty>
as opposed to:
<className xlmns="Whatever">
<firstProperty>firstPropertyValue</firstProperty>
<secondProperty>secondPropertyValue</secondProperty>
</className>
My code looks like this:
private static string GetRow<T>(object _data)
{
StringBuilder xml = new StringBuilder();
T data = (T)_data;
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlSerializer serialiser = new XmlSerializer(typeof(T));
XmlWriter writer = XmlWriter.Create(xml, settings);
serialiser.Serialize(writer, data, null);
return xml.ToString();
}
My first thought was that the OmitXmlDeclaration setting would do the job - it doesn't unless you set ConformanceLevel to Fragment. The problem is, once I do set the ConformanceLevel, I get the following run-time error:
"
Quote:
"WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment."
So it would appear that XmlSerializer.Serialize() is calling WriteStartDocument regardless of ConformanceLevel being set to Fragment rather than Document.
I suspect that the easiest way around this will be to write my own serialiser but I'd be interested to know if there is actually a way of successfully producing a fragment from the XmlSerializer class.