0

My application has a feature which involves saving some UI Elements that have been creating in order to recreate them the next time the user launches the application.

To do so, it saves The UI Element Object using the XamlWriter.Save function, and then saves that string to an XML file. I can successfully retrieve the string it saves.

For example, here's a button that was serialized and saved:

<Button Name="Thumb1" Grid.Column="0" Grid.Row="0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:swi="clr-namespace:System.Windows.Interop;assembly=PresentationCore" xmlns:s="clr-namespace:System;assembly=mscorlib"><Button.Tag><s:Int32>0</s:Int32></Button.Tag><Image Stretch="UniformToFill" Width="380" Height="213" HorizontalAlignment="Center" VerticalAlignment="Center"><Image.Source><swi:InteropBitmap /></Image.Source></Image></Button>

However, when I try to load this data back in using the following code, I get a XamlParseException, which says that "Data at the root level is invalid. Line 1, position 1."

using (StringReader SR = new StringReader(Attribute) )
{
    using (XmlReader XR = XmlReader.Create(SR) )
    {
        InMedButton = (System.Windows.Controls.Button)XamlReader.Load(XR);
    }
};

This is a code snippet I got from Microsoft docs here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.markup.xamlwriter?view=netcore-3.1

I feel like it may not be serializing the XAML properly, as it's not formatted in a tree-like structure like XML or XAML normally are, but I don't know.

How would I properly deserialize and load XAML?

BBonless
  • 97
  • 7
  • You have to read in the reverse order you wrote the data. There is something inconsistent between the write code and the read code. – jdweng Jul 08 '20 at 16:36
  • You should create your ui as a string in the first place and xamlreader.parse it into ui. You can then save your string to a file on disk. Xamlwriter save has some serious limitations. – Andy Jul 08 '20 at 17:32
  • @jdweng Reversing the string didn't fix it, unfortunately. I do see the difference between the w/r code. When written to XML some characters like > or " are encoded differently. I guess a function to fix that may work – BBonless Jul 08 '20 at 19:52
  • @Andy How would I make it as a string? – BBonless Jul 08 '20 at 19:53
  • I didn't say reverse the string. – jdweng Jul 08 '20 at 22:56

1 Answers1

0

As jdweng made me realize, XML formats certain characters differently. In my case '<', '>', '&', and '"' were all replaced to specific character codes in XML, which I thought was the Serializer's fault. Making a function to replace these codes with their respective characters fixed it.

BBonless
  • 97
  • 7