开发者

Writing out FlowDocument xaml with namespace using XmlWriter

I've got a collection of data that needs to be converted to a .xaml file that can later be loaded as a FlowDocument into a FlowDocumentReader. I don't directly instantiate Paragraphs, Runs, rather I generate the xaml to create the document later.

What I've tried:

I iterate through the data, creating XElements for Paragraphs, Runs, InlineUIContainers, etc. and build up the FlowDocument structure just fine and then call:

XmlWriter writer = XmlW开发者_开发问答riter.Create("output.xaml");
flowDocElem.WriteTo(writer);
writer.Close();

In the consuming app, I do this:

flowDocument = XamlReader.Load(xamlFile) as FlowDocument;
flowDocumentReader.Document = flowDocument;
xamlFile.Close();

But the loading fails because it doesn't know what a FlowDocument is. The FlowDocument element looks like so:

<FlowDocument Name="testDoc">

(There's no namespace there to shed light as to what a FlowDocument is when it is read in.)

If I hand edit the .xaml and modify the element to be:

<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Name="testDoc">

Then it'll load just fine.

When creating the XElement for the FlowDocument, I've tried to do this:

new XElement("FlowDocument", new XAttribute("Name", "testDoc"), new XAttribute("xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"));

but that doesn't work either - gives me an error if I try to create the namespace attribute.

I can completely cheat and stuff that xmlns into the element and then call something like

File.WriteAllText("output.xaml", fixedTxt);

but that feels dirty and so I think I'm just plain doing it wrong.

Thoughts?


Update:

While this probably isn't the prescriptive solution to the problem, it does work:

By adding a ParserContext to the XamlReader, I was able to get past the problem with loading the FlowDocument xml.

FileStream xamlFile = new FileStream("output.xaml", FileMode.Open, FileAccess.Read);
XamlReader x = new XamlReader();
ParserContext parserContext = new ParserContext();
parserContext.XmlnsDictionary.Add("","http://schemas.microsoft.com/winfx/2006/xaml/presentation");
flowDocument = XamlReader.Load(xamlFile, parserContext) as FlowDocument;
flowDocumentReader.Document = flowDocument;
xamlFile.Close();


Try using XamlWriter instead of XmlWriter.


If you use XLinq you should try the following:

XNamespace ns = @"http://schemas.microsoft.com/winfx/2006/xaml/presentation";
XNamespace xns = @"http://schemas.microsoft.com/winfx/2006/xaml";
XElement someElement = new XElement(ns + "FlowDocument",
                           new XAttribute(xns + "Name", name),
                           ...);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜