Tar
Tar

Reputation: 9025

How to serialize XAML as part of other plain XML nodes?

I want to serialize XAML and other app's-settings-info in a single settings-file. Something like:

<root>
    <settings>
        ...
    </settings>
    <xaml_stuff>
        ...
    </xaml_stuff>
</root>

I'll be thankful for any guidance how to elegantly accomplish it: I have XamlWriter on one hand and the other XML-API\namespaces on the other, but I can't find a way to connect them together.

Upvotes: 0

Views: 322

Answers (1)

K Mehta
K Mehta

Reputation: 10553

See if this helps: http://msdn.microsoft.com/en-us/library/ms590446.aspx.

From what I understand, it first serializes it to XmlWriter, which you can then use to add other non-xaml stuff

Edit: Here's a concrete C# example (with some changes to what I said previously)...

XmlTextWriter w = new XmlTextWriter("test.xml", Encoding.UTF8);
w.WriteStartElement("root");
w.WriteAttributeString("xmlns", "x");
w.WriteStartElement("item1");
w.WriteEndElement();
w.WriteStartElement("item2");
w.WriteEndElement();

Button btn = new Button();
btn.Content = "Test Button";
btn.Width = 200;
btn.Height = 100;
btn.Foreground = Brushes.Green;

string buf = XamlWriter.Save(btn);
XmlTextReader reader = new XmlTextReader(new StringReader(buf));
reader.Read();
w.WriteNode(reader, true);

w.WriteEndElement();
w.Flush();
w.Close();

And here are the contents of the file it generates:

<root xmlns="x">
    <item1 />
    <item2 />
    <Button Foreground="#FF008000" Width="200" Height="100" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">Test Button</Button>
</root>

Upvotes: 1

Related Questions