我正在尝试将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);
}
}
}
最佳答案
正如@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"
可用于制表符。