LoginSignup
1
0

More than 5 years have passed since last update.

XML 文字列にインデントつき整形を施す(System.Xml.XmlWriter編)

Last updated at Posted at 2019-02-18

はじめに

@kobake@github さんの投稿(感謝!)「C# で XmlDocument からインデント付きの整形文字列を得る」にお世話になっていましたが、私の最近の環境で XmlTextWriter クラスがなぜかインテリセンスに上がってこなくなってしまったため、Microsoft オンラインマニュアルに「.NET Framework 2.0 以降では、代わりに XmlWriter クラスを使用することをお勧めします。」と記載されていることもあり、急遽書き換えをしてみました。整形仕様は、XmlWriteSetting クラスのオブジェクトで指定します。

コード

namespace App
{
    public class Class1
    {
        private static string GetFormattedXmlText(string s)
        {
            var v = new System.Xml.XmlDocument();
            v.LoadXml(s);

            var ws = new System.Xml.XmlWriterSettings();
            ws.Indent = true;
            ws.IndentChars = "  "; // <- インデントの空白数ではなくて、1つ分のインデントとして使う文字列を直接指定します。

            using (var ms = new System.IO.MemoryStream())
            {
                using (var wr = System.Xml.XmlWriter.Create(ms, ws))
                {
                    v.WriteContentTo(wr);
                    wr.Flush();
                    ms.Flush();
                }
                ms.Position = 0;
                using (var rd = new System.IO.StreamReader(ms))
                {
                    return rd.ReadToEnd();
                }
            }
        }
    }
}

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0