如何在使用XDocument编写XML时更改用于缩进的字符数

本文关键字:用于 缩进 字符 XML 编写 XDocument | 更新日期: 2023-09-27 18:29:21

我正在尝试将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);
        }
    }
}

如何在使用XDocument编写XML时更改用于缩进的字符数

正如@John Saunders和@sa_ddam213所指出的,new XmlWriter是不推荐使用的,所以我深入研究了一下,并学习了如何使用XmlWriterSettings更改缩进。我从@sa_ddam213得到了using语句的想法。

我用以下内容替换了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"即可用于选项卡。