15

It is simple enough to put the outer text of an XML node in a WPF text box. But is there a way to get the text box to format the text as an XML document? Is there a different control that does that?

3 Answers 3

28

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

5

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);
}

Comments

5

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

4 Comments

This only works on XML files, not on in-memory XML variables
@DdW Yes one would have to save to a temporary file if the XML is in memory.
A little late to the party, but you can do WebBrowser.NavigateToString to display an in-memory XML. No need to save to a temp file. I found this the absolute easiest and nicest way to visualize XML in WPF
@hcd Sounds good. Let the others know, so If you want you can update my answer with an example or provide an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.