Подтвердить что ты не робот

Как изменить количество символов, используемых для отступов при записи XML с помощью XDocument

Я пытаюсь изменить отступ по умолчанию 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);
        }
    }
}
4b9b3361

Ответ 1

Как отмечал @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" для вкладки.