XDocument 在解析时自动缩进文件,并且在保存时不会删除缩进

Shi*_*chi 3 c# xml indentation linq-to-xml visual-studio

我正在寻求有关使用 XDocument(不是 XMLDocument)保存 XML 文件的帮助。

所以我有一个没有缩进的xml文件(实际上它是1行)。当我使用 XDocument.Parse 将其读取到 XDocument 时(在使用 读取和存储字符串之后StreamReader),生成的 XDocument 是缩进的。

好吧,我想只要能不缩进地保存回文件就可以了。然而,尽管我有

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.NewLineOnAttributes = false;
writerSettings.NewLineHandling = NewLineHandling.None;
writerSettings.Indent = false;
Run Code Online (Sandbox Code Playgroud)

并在我创建 XmlWriter 时将其传入

using (var writer = XmlWriter.Create(u.ToFileSystemPath(), settings))
{
    xd.Save(writer);
}
Run Code Online (Sandbox Code Playgroud)

生成的 XML 文件仍然有缩进。当我在 Visual Studio 上调试时,我注意到这writer是一个类XmlWellFormedWriter. 这和我的结果有关系吗?任何帮助,将不胜感激。

谢谢。

phi*_*lip 5

Save()SaveOptions 在以及 上均可用ToString()

    string xmlstring = 
@"<Top>
    <First>1</First>
    <Second>Dude</Second>
    <Third>Now</Third>
</Top>";

    XDocument doc = XDocument.Parse(xmlstring);
    doc.Save(@"C:\temp\noIndet.xml", SaveOptions.DisableFormatting);
        // string noIndent = doc.ToString(SaveOptions.DisableFormatting);
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述