65.9K
CodeProject 正在变化。 阅读更多。
Home

格式化 XML – 代码片段

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.82/5 (29投票s)

2007年1月14日

viewsIcon

84192

如何快速格式化 XML 以获得更美观的显示效果。

引言

我知道这对于很多人来说是基础知识,但由于我找不到本网站上类似的文档,所以我分享了这个有用的代码片段,供那些不太熟悉 Xml 类的人使用。

基本上,我想要一个快速简便的方法,将未格式化的 XML 字符串转换为可以在文本框中(例如,带有缩进和换行符)美观显示的内容,而无需进行太多繁琐的操作。

使用代码

很简单。只需调用该方法并显示结果,例如,在 Windows 窗体文本框中。在 Webform 元素中显示可能需要更改换行符,这可以使用 String.Replace 轻松完成。

代码

using System.Text;
using System.Xml;

. . .

/// <summary>

/// Returns formatted xml string (indent and newlines) from unformatted XML

/// string for display in eg textboxes.

/// </summary>

/// <param name="sUnformattedXml">Unformatted xml string.</param>

/// <returns>Formatted xml string and any exceptions that occur.</returns>


private string FormatXml(string sUnformattedXml)
{
    //load unformatted xml into a dom

    XmlDocument xd = new XmlDocument();
    xd.LoadXml(sUnformattedXml);

    //will hold formatted xml

    StringBuilder sb = new StringBuilder();

    //pumps the formatted xml into the StringBuilder above

    StringWriter sw = new StringWriter(sb);

    //does the formatting

    XmlTextWriter xtw = null;

    try
    {
        //point the xtw at the StringWriter

        xtw = new XmlTextWriter(sw);

        //we want the output formatted

        xtw.Formatting = Formatting.Indented;

        //get the dom to dump its contents into the xtw 

        xd.WriteTo(xtw);
    }
    finally
    {
        //clean up even if error

        if (xtw != null)
            xtw.Close();
    }

    //return the formatted xml

    return sb.ToString();
}

祝您编码愉快!

© . All rights reserved.