Display XML in a WPF textbox Display XML in a WPF textbox wpf wpf

Display XML in a WPF textbox


This should do the trick:

    protected string FormatXml(string xmlString)    {        XmlDocument doc = new XmlDocument();        doc.LoadXml(xmlString);        StringBuilder sb = new StringBuilder();        System.IO.TextWriter tr = new System.IO.StringWriter(sb);        XmlTextWriter wr = new XmlTextWriter(tr);        wr.Formatting = Formatting.Indented;        doc.Save(wr);        wr.Close();        return sb.ToString();    }


You can attach to the binding a converter and call inside the converter to formatting code.

This is example code that formats XML:

public string FormatXml(string xml){    var doc = new XmlDocument();    doc.LoadXml(xml);    var stringBuilder = new StringBuilder();    var xmlWriterSettings = new XmlWriterSettings                                  {Indent = true, OmitXmlDeclaration = true};    doc.Save(XmlWriter.Create(stringBuilder, xmlWriterSettings));    return stringBuilder.ToString();}

And a test demonstrates the usage:

public void TestFormat(){    string xml = "<root><sub/></root>";    string expectedXml = "<root>" + Environment.NewLine +                         "  <sub />" + Environment.NewLine +                         "</root>";    string formattedXml = FormatXml(xml);    Assert.AreEqual(expectedXml, formattedXml);}


Is there a different control that does that?

Yes, just display the xml in a browser control.

<WebBrowser x:Name="wbOriginalXml" />

Simply navigate to a saved xml

wbOriginalXml.Navigate( new Uri(@"C:\TempResult\Manifest.xml") );

The results are automatically tree-ed in the browser where the nodes can be collapsed:

enter image description here