格式化 XML 字符串以打印友好的 XML 字符串 [英] Format XML string to print friendly XML string

查看:34
本文介绍了格式化 XML 字符串以打印友好的 XML 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 XML 字符串:

I have an XML string as such:

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

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

There are no lines between one element and another, and thus is very difficult to read. I want a function that formats the above string:

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

不用自己手动编写格式化函数,有没有我可以随意使用的 .Net 库或代码片段?

Without resorting to manually write the format function myself, is there any .Net library or code snippet that I can use offhand?

推荐答案

使用 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;
}

这篇关于格式化 XML 字符串以打印友好的 XML 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆