KiMoGiGi 技术文集

不在乎选择什么,而在乎坚持多久……

IT博客 首页 联系 聚合 管理
  185 Posts :: 14 Stories :: 48 Comments :: 0 Trackbacks
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 />""&nbsp;&nbsp;&nbsp;&nbsp;");
            
string format = fxs.FormatString(rawXml, Encoding.UTF8);
            Console.WriteLine(format);
        }
    }
posted on 2011-03-16 11:49 KiMoGiGi 阅读(490) 评论(0)  编辑 收藏 引用 所属分类: C# / Winforms
只有注册用户登录后才能发表评论。