Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display XML in a WPF textbox

Tags:

xml

wpf

textbox

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?

like image 882
epotter Avatar asked Nov 09 '09 18:11

epotter


2 Answers

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();
    }
like image 150
pattersonc Avatar answered Sep 21 '22 06:09

pattersonc


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);
}
like image 24
Elisha Avatar answered Sep 18 '22 06:09

Elisha