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
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();
}
Comments
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
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:
4 Comments
DdW
This only works on XML files, not on in-memory XML variables
ΩmegaMan
@DdW Yes one would have to save to a temporary file if the XML is in memory.
hcd
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
ΩmegaMan
@hcd Sounds good. Let the others know, so If you want you can update my answer with an example or provide an answer.
