jms*_*ker 15 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 writer = new XmlTextWriter(destinationFile, null);
writer.Indentation = 3;
writer.WriteStartDocument();
// Add elements, etc
writer.WriteEndDocument();
writer.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于我使用的另一个项目,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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
jms*_*ker 21
正如@John Saunders和@ sa_ddam213所指出的那样,new XmlWriter
我已经弃用了,所以我深入挖掘并学会了如何使用XmlWriterSettings更改缩进.using
我从@ 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);
}
Run Code Online (Sandbox Code Playgroud)
这给了我需要的3个空间缩进.如果需要更多空格,只需将它们添加到IndentChars
或"\t"
可用于制表符.