小编典典

格式化XML字符串以打印友好的XML字符串

c#

我有这样的XML字符串:

<?xml version='1.0'?><response><error code='1'> Success</error></response>

一个元素和另一个元素之间没有线条,因此很难阅读。我想要一个格式化上述字符串的函数:

<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response>

无需自己动手编写格式函数,是否有任何我可以立即使用的.Net库或代码段?


阅读 249

收藏
2020-05-19

共1个答案

小编典典

使用XmlTextWriter

public static string PrintXML(string xml)
{
    string result = "";

    MemoryStream mStream = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
    XmlDocument document = new XmlDocument();

    try
    {
        // Load the XmlDocument with the XML.
        document.LoadXml(xml);

        writer.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter
        document.WriteContentTo(writer);
        writer.Flush();
        mStream.Flush();

        // Have to rewind the MemoryStream in order to read
        // its contents.
        mStream.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader sReader = new StreamReader(mStream);

        // Extract the text from the StreamReader.
        string formattedXml = sReader.ReadToEnd();

        result = formattedXml;
    }
    catch (XmlException)
    {
        // Handle the exception
    }

    mStream.Close();
    writer.Close();

    return result;
}
2020-05-19