将XML节点的外部文本放在WPF文本框中非常简单。但有没有办法让文本框将文本格式化为XML文档?有不同的控制吗?
答案 0 :(得分:24)
这应该可以解决问题:
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();
}
答案 1 :(得分:5)
您可以将转换器附加到转换器,并在转换器内调用格式化代码。
这是格式化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();
}
测试证明了用法:
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);
}
答案 2 :(得分:3)