C# 如何更改使用XDocument编写XML时用于缩进的字符数
我试图将XDocument的默认缩进从2更改为3,但我不太确定如何继续。如何做到这一点 我熟悉C# 如何更改使用XDocument编写XML时用于缩进的字符数,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我试图将XDocument的默认缩进从2更改为3,但我不太确定如何继续。如何做到这一点 我熟悉XmlTextWriter,并使用过这样的代码: using System.Xml; namespace ConsoleApp { class Program { static void Main(string[] args) { string destinationFile = "C:\myPath\results.xml";
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);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Xml.Linq;
使用System.Xml;
使用系统文本;
名称空间控制台
{
班级计划
{
静态void Main(字符串[]参数)
{
//源文件的缩进为3
字符串sourceFile=@“C:\myPath\source.xml”;
字符串destinationFile=@“C:\myPath\results.xml”;
列表设备=新列表();
XDocument template=XDocument.Load(源文件);
//添加元素等
template.Save(destinationFile);
}
}
}
正如@John Saunders和@sa_ddam213所指出的,新的XmlWriter
已被弃用,因此我进行了更深入的研究,并学习了如何使用XmlWriterSettings更改缩进。我从@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个空格缩进。如果需要更多的空格,只需将它们添加到缩进字符中即可。XmlWriter
或“\t”
可用于制表符。Save
采用XmlWriter
…-+1,很好的发现,我删除了我的,因为我收到了很多负面反馈,您的解决方案是一个很好的解决方案,而不是使用旧的XmlTextWriter