Display XML in a WPF textbox
It is simple enou开发者_运维问答gh 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?
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:
精彩评论