我试图将XDocument的默认缩进从2更改为3,但我不太确定如何继续。如何做到这一点
我熟悉XmlTextWriter,并使用过这样的代码:
使用System.Xml;
名称空间控制台
{
班级计划
{
静态void Main(字符串[]参数)
{
string destinationFile=“C:\myPath\results.xml”;
XmlTextWriter=新的XmlTextWriter(destinationFile,null);
writer.Indentation=3;
writer.WriteStartDocument();
//添加元素等
writer.WriteEndDocument();
writer.Close();
}
}
}
对于另一个项目,我使用了XDocument,因为它更适合我的实现,类似于:
使用系统;
使用System.Collections.Generic;
使用System.Xml.Linq;
使用System.Xml;
使用系统文本;
名称空间控制台
{
班级计划
{
静态void Main(字符串[]参数)
{
//源文件的缩进为3
字符串[email protected]“C:\myPath\source.xml”;
字符串[email protected]“C:\myPath\results.xml”;
列表<;XElement>;设备=新列表<;XElement>;();
XDocument template=XDocument.Load(源文件);
//添加元素等
template.Save(destinationFile);
}
}
}
正如@John Saunders和@sa_ddam213所指出的,新的XmlWriter已被弃用,因此我进行了更深入的研究,并学习了如何使用XmlWriterSettings更改缩进。我从@sa_ddam213获得的使用语句的想法
我替换了template.Save(destinationFile)包含以下内容:
XmlWriterSettings设置=新的XmlWriterSettings();
settings.Indent=true;
settings.IndentChars=“”;//缩进3个空格
使用(XmlWriter=XmlTextWriter.Create(目标文件,设置))
{
模板保存(编写器);
}
这给了我需要的3个空格缩进。如果需要更多的空格,只需将它们添加到缩进中即可。chars或“\t”可用于制表符