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

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);
        }
    }
}

“Save” 接受 XmlWriter... - http://msdn.microsoft.com/zh-cn/library/bb336977.aspx - Alexei Levenkov
1个回答

23

正如 @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);
}

这给了我所需的三个空格缩进。如果需要更多的空格,只需将它们添加到IndentChars中或使用制表符"\t"

+1,好发现,我已经删除了我的代码,因为我得到了很多负面反馈,而你的解决方案是一个不错的变通方法,除了使用旧的XmlTextWriter - sa_ddam213

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接