If you’d like to render XML as a WPF FlowDocument, give this a try (ClickOnce sample; source available here or on CodePlex). Here’s a screenshot:
The useful part is the PrettyXmlConverter class (view here; it’s "self documenting"
). It’s implemented as an IValueConverter so you can easily include it in binding expressions:
<Window x:Class="XmlFlowDocumentSample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:converters="clr-namespace:CJC.Wpf.Converters" Title="Pretty XML FlowDocument sample"> <Window.Resources> <converters:PrettyXmlConverter x:Key="prettyXmlConverter"/> <XmlDataProvider x:Key="xmlSource" Source="Xml/Books.xml" IsAsynchronous="False"/> </Window.Resources> <Grid> <FlowDocumentReader ViewingMode="Scroll" Zoom="300" Document="{Binding Source={StaticResource xmlSource}, Path=Document, BindsDirectlyToSource=true, Converter={StaticResource prettyXmlConverter}}"> </FlowDocumentReader> </Grid> </Window>
Currently it only renders elements and attributes, so no comments, processing instructions or explicit CDATA handling. These could be added very easily if needed
The formatted XML pastes nicely into MS Word (formatting preserved).



7 comments
Comments feed for this article
November 2, 2008 at 3:54 am
Silverlight Travel
Thanks for your nice “PrettyXmlConverter” class. It is a great help.
Peter Loebel
November 12, 2008 at 10:42 am
Bradley Grainger
Thanks for providing this great class; it does its job well and is really easy to plug into an existing project.
November 12, 2008 at 10:47 am
Chris Cavanagh
Peter & Bradley – Thanks! Let me know if you make any improvements / enhancements
November 26, 2008 at 2:24 pm
tim
Perfect. Thank you!
May 17, 2010 at 1:50 pm
marlon cruz
Thanks for sharing this information. However, i have question… using your source code is it possible to load the xml document w/o the element ” tags? only the contents.
I’m a newbie in this approach but i wanted to see how i can load a simple XML file to a flowdocument.
Thanks
May 18, 2010 at 6:55 am
Chris Cavanagh
marlon – Are you wanting to omit the root element? (“catalog” in the screenshot above).
May 18, 2010 at 9:16 am
marlon
Yes Chris. I wanted to omit the element not only the root element ‘catalog’ from your sample xml but also the child elements. Is there a way to achieve that? If does, please assist me.
I highly appreciate your quick response.
Thanks again and more power.