16

XDocument のデフォルトのインデントを 2 から 3 に変更しようとしていますが、どうすればよいかわかりません。これはどのように行うことができますか?

私はそれに精通してXmlTextWriterおり、そのようなコードを使用しています:

using System.Xml;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string destinationFile = "C:\myPath\results.xml";
            XmlTextWriter writer = new XmlTextWriter(destinationFile, null);
            writer.Indentation = 3;
            writer.WriteStartDocument();

            // Add elements, etc

            writer.WriteEndDocument();
            writer.Close();
        }
    }
}

私が使用した別のプロジェクトではXDocument、これに似た実装でうまく機能するためです。

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml;
using System.Text;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Source file has indentation of 3
            string sourceFile = @"C:\myPath\source.xml";
            string destinationFile = @"C:\myPath\results.xml";

            List<XElement> devices = new List<XElement>();

            XDocument template = XDocument.Load(sourceFile);        

            // Add elements, etc

            template.Save(destinationFile);
        }
    }
}
4

1 に答える 1

22

@John Saunders と @sa_ddam213 が指摘したように、new XmlWriterは推奨されていないので、もう少し掘り下げて、XmlWriterSettings を使用してインデントを変更する方法を学びました。using@sa_ddam213 から得たステートメントのアイデア。

私は次のものに置き換えtemplate.Save(destinationFile);ました:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "   ";  // Indent 3 Spaces

using (XmlWriter writer = XmlTextWriter.Create(destinationFile, settings))
{                    
    template.Save(writer);
}

これにより、必要な 3 つのスペースのインデントが得られました。さらにスペースが必要な場合は、タブに追加するIndentChars"\t"、タブに使用できます。

于 2013-08-29T05:23:35.147 に答える