使用UTF-8 XML声明可自定义的Pretty XML输出
以下类定义提供了一种简单的方法,该方法将输入XML字符串转换为xml声明为UTF-8的格式化输出XML。它支持XmlWriterSettings类提供的所有配置选项。
using System;
using System.Text;
using System.Xml;
using System.IO;
namespace CJBS.Demo
{
public static class PrettyXmlFormatter
{
public static string GetPrettyXml(XmlDocument doc)
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
, IndentChars = " "
, NewLineChars = System.Environment.NewLine
, NewLineHandling = NewLineHandling.Replace
};
StringWriterWithEncoding sw = new StringWriterWithEncoding(Encoding.UTF8);
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
doc.Save(writer);
}
return sw.ToString();
}
private sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
public override Encoding Encoding
{
get { return encoding; }
}
}
}
}
进一步改进的可能性:
GetPrettyXml(XmlDocument doc, XmlWriterSettings settings)
可以创建允许调用者自定义输出的其他方法。
GetPrettyXml(String rawXml)
可以添加其他方法来支持解析原始文本,而不是让客户端使用XmlDocument。就我而言,我需要使用XmlDocument来操纵XML,因此没有添加它。
用法:
String myFormattedXml = null;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(myRawXmlString);
myFormattedXml = PrettyXmlFormatter.GetPrettyXml(doc);
}
catch(XmlException ex)
{
// Failed to parse XML -- use original XML as formatted XML
myFormattedXml = myRawXmlString;
}