I'm trying to use XamlWriter
to write custom objects to XML. I'm trying to do this because I find the default XmlSerializer
a pain because of BindingFailures, missing XmlInclude, etc.
So far I'm pleased with how clean the XamlWriter
writes to XML and how it worked with no changes to my data classes. For example, here's the output of my custom Document
class containing a list of Step
objects:
<Document xmlns="clr-namespace:XamlWriterTest;assembly=XamlWriterTest"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<Document.Steps>
<SyncStep
SyncData="True" />
</Document.Steps>
</Document>
Now I want to simplify the XAML further by removing the <Document.Steps>
markup because its superfluous. So I know I should be using the ContentPropertyAttribute
, but it doesn't make the <Document.Steps>
go away.
Here's the data class I serialize:
[ContentProperty("Steps")]
public class Document
{
public Document()
{
Steps = new ObservableCollection<Step>();
}
public ObservableCollection<Step> Steps { get; set; }
}
And here's the code to serialize:
static void Main(string[] args)
{
Document doc = new Document();
SyncStep syncStep = new SyncStep();
syncStep.SyncData = true;
doc.Steps.Add(syncStep);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineHandling = NewLineHandling.Entitize;
settings.OmitXmlDeclaration = true;
settings.NewLineOnAttributes = true;
StringBuilder sb = new StringBuilder();
XmlWriter xw = XmlWriter.Create(sb, settings);
XamlWriter.Save(doc, xw);
Console.Write(sb.ToString());
Console.ReadLine();
}
Is there something I am missing for the ContentProperty
attribute to get used properly?