How do I parse a non-GUI XAML file?

225 views Asked by At

Ok, so here's what I want to do.

  1. Create a "configuration file" using XAML 2009. It would look something like this:

    <TM:Configuration 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:tm="clr-namespace:Test.Monkey;assembly=Test.Monkey" 
    >
        <TM:Configuration.TargetFile>xxxx</TM:Configuration.TargetFile>
    <TM:Configuration 
    
  2. Parse this file at runtime in order to get the object-graph.

1

There are 1 answers

0
Jonathan Allen On BEST ANSWER

Easy way:

var z = System.Windows.Markup.XamlReader.Parse(File.ReadAllText("XAMLFile1.xaml"));

(Turns out this does support XAML 2009 after all.)

Hard way, but with less dependencies:

var x = ParseXaml(File.ReadAllText("XAMLFile1.xaml"));

    public static object ParseXaml(string xamlString)
    {
        var reader = new XamlXmlReader(XmlReader.Create(new StringReader(xamlString)));
        var writer = new XamlObjectWriter(reader.SchemaContext);
        while (reader.Read())
        {
            writer.WriteNode(reader);
        }
        return writer.Result;
    }

Creating XAML from object graph:

    public static string CreateXaml(object source)
    {
        var reader = new XamlObjectReader(source);
        var xamlString = new StringWriter();
        var writer = new XamlXmlWriter(xamlString, reader.SchemaContext);
        while (reader.Read())
        {
            writer.WriteNode(reader);
        }
        writer.Close();
        return xamlString.ToString();
    }

Notes:

  1. Fully qualify all namespaces. It has problem finding local assemblies by namespace only.
  2. Consider using the ContentPropertyAttribute.
  3. Useful notes on XAML 2009: http://wpftutorial.net/XAML2009.html