C# 格式化XML方法

 

/// <summary>
/// 格式化XML方法
/// </summary>

public class UXMLFormat
{
    public static string FormatXML(string XMLstring)
    {
        //校验是否是XML报文
        if (!XMLstring.Contains("<?xml version")) return XMLstring;
        XmlDocument xmlDocument = GetXmlDocument(XMLstring);
        return ConvertXmlDocumentTostring(xmlDocument);
    }
    public static string ConvertXmlDocumentTostring(XmlDocument xmlDocument)
    {
        MemoryStream memoryStream = new MemoryStream();
        XmlTextWriter writer = new XmlTextWriter(memoryStream, null)
        {
            Formatting = Formatting.Indented//缩进
        };
        xmlDocument.Save(writer);
        StreamReader streamReader = new StreamReader(memoryStream);
        memoryStream.Position = 0;
        string xmlString = streamReader.ReadToEnd();
        streamReader.Close();
        memoryStream.Close();
        return xmlString;
    }
        public static XmlDocument GetXmlDocument(string xmlString)
    {
        XmlDocument document = new XmlDocument();
        document.LoadXml(xmlString);
        return document;
    }
}

 

 

引用 C#   格式化XML方法

posted @ 2019-09-04 21:01  quanzhan  阅读(3627)  评论(0编辑  收藏  举报