C#.net 格式化输出XML文档字符串

时间:2022-11-18 19:56:54


试用登录http://121.18.78.216/

 

        /// <summary>
        /// 返回经过格式化处理的xml文档
        /// </summary>
        /// <param name="doc">xml文档对象</param>
        /// <returns></returns>
        public static string GetFormatXml(XmlDocument doc)
        {
            string result = null;
            if (doc != null)
            {
                try
                {
                    MemoryStream mstream = new MemoryStream(1024);
                    XmlTextWriter writer = new XmlTextWriter(mstream, null);
                    writer.Formatting = Formatting.Indented;//微软提供的
                    doc.WriteTo(writer);
                    writer.Flush();
                    writer.Close();

                    Encoding encoding = Encoding.GetEncoding("utf-8");
                    result = encoding.GetString(mstream.ToArray());
                    mstream.Close();
                }
                catch
                {

//只能实现换行
                    result = doc.OuterXml.Replace(">/r/n", ">").Replace(">", ">/r/n");
                }
            }
            return result;
        }