How do I parse a non-GUI XAML file?
Ok, so here's what I want to do.
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:Con开发者_开发问答figuration.TargetFile>xxxx</TM:Configuration.TargetFile> <TM:Configuration
Parse this file at runtime in order to get the object-graph.
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:
- Fully qualify all namespaces. It has problem finding local assemblies by namespace only.
- Consider using the ContentPropertyAttribute.
- Useful notes on XAML 2009: http://wpftutorial.net/XAML2009.html
精彩评论