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方法

C# 格式化XML方法

上一篇:Vue(十一)---特殊attribute


下一篇:(五十五)c#Winform自定义控件-管道