LoginSignup
6
6

More than 5 years have passed since last update.

C# で XmlDocument からインデント付きの整形文字列を得る

Posted at

System.Xml.XmlDocument を整形済み文字列(インデント付き)に変換する方法。

整形関数

public static string FormatXmlDocument(XmlDocument xmlDocument)
{
    MemoryStream stream = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Unicode);

    // indent setting
    writer.Formatting = Formatting.Indented;
    writer.Indentation = 2; // indent length
    writer.IndentChar = ' '; // indent character

    // formatting write
    xmlDocument.WriteContentTo(writer);
    writer.Flush();
    stream.Flush();
    stream.Position = 0;

    // to string
    StreamReader reader = new StreamReader(stream);
    string formattedXml = reader.ReadToEnd();

    return formattedXml;
}

writer.Indentation でインデント幅を設定できます。今回は 2 にしておく。

使用例

public static void Main()
{
    // 日本語化けないようにする
    Console.OutputEncoding = new UTF8Encoding();

    // サンプルXML構築 (整形を確認するために意図的に崩してある)
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(@"<?xml version=""1.0""?>
        <catalog><book id=""bk101"">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        </book>
        <book id=""bk102""><author>Ralls, Kim</author>
        <title>ほげほげ</title></book></catalog>");

    // インデント付き整形表示
    Console.WriteLine("----------------------------------------");
    Console.WriteLine(FormatXmlDocument(xmlDocument));
    Console.WriteLine("----------------------------------------");
}

サンプルXML は サンプル XML ファイル (books.xml) から拾ってきたものをちょっといじって使ってます。

出力結果

----------------------------------------
<?xml version="1.0"?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>ほげほげ</title>
  </book>
</catalog>
----------------------------------------

見やすい形になりました。

参考

6
6
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
6
6