public class FormatXmlString
{
string newline = default(string);
string tab = default(string);
public FormatXmlString()
:this(Environment.NewLine, "\t")
{
}
public FormatXmlString(string newline, string tab)
{
this.newline = newline;
this.tab = tab;
}
public string FormatString(string xmlString, Encoding encoding)
{
XmlDocument document = new XmlDocument();
document.LoadXml(xmlString);
StringBuilder formatString = new StringBuilder();
XmlWriterSettings setting = new XmlWriterSettings();
setting.CheckCharacters = false;
setting.Encoding = encoding;
setting.Indent = true;
setting.IndentChars = this.tab.ToString();
setting.NewLineChars = this.newline;
using (XmlWriter writer = XmlWriter.Create(formatString, setting))
{
document.WriteTo(writer);
}
return formatString.ToString();
}
}
class MyClass
{
public static void Test()
{
string rawXml = @"<?xml version=""1.0"" encoding=""UTF-8"" ?><root><head><serviceName>aaaa</serviceName><v>1.0</v></head><body><clientId>10</clientId><clientIdExt>1701</clientIdExt>
<clientIp>192.168.1.1</clientIp><timeToken>20110315103732140</timeToken><serviceId>000</serviceId><loginType>1</loginType>
<loginName>testtest</loginName><loginPassword>111111</loginPassword></body></root>";
//FormatXmlString fxs = new FormatXmlString();
FormatXmlString fxs = new FormatXmlString("<br />", " ");
string format = fxs.FormatString(rawXml, Encoding.UTF8);
Console.WriteLine(format);
}
}