c# - 使用 XElement 保存 XML 文件时,文件中的对齐方式也会发生变化,如何避免?

标签 c# xml whitespace xelement

我正在使用

XElement root = XElement.Load(filepath);

加载 XML 文件,然后找到我需要的东西。

IEnumerable<XElement> commands = from command in MyCommands
                                 where (string) command.Attribute("Number") == Number
                                 select command;

foreach (XElement command in commands)
{
     command.SetAttributeValue("Group", GroupFound);
}

完成更改后,我使用以下代码保存文件。

root.Save(filepath);

保存文件时,我的 XML 文件中的所有行都会受到影响。 Visual Studio 默认对齐所有行,但我需要保存原始文件格式。

我无法更改文档的任何部分,除了组属性值。

command.SetAttributeValue("Group") attributes.

最佳答案

你需要做的:

XElement root = XElement.Load(filepath, LoadOptions.PreserveWhitespace);

然后做:

root.Save(filepath, SaveOptions.DisableFormatting);

这将通过使用 LoadOptions 保留您的原始空白和 SaveOptions .

关于c# - 使用 XElement 保存 XML 文件时,文件中的对齐方式也会发生变化,如何避免?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155516/

相关文章:

javascript - 使用jQuery创建调查 - 任何示例?

c# - 使用 XElement 从自定义 XML 反序列化 `Dictionary<string, Tuple<string, List<string>>>`

java - 从 Wordpress 提要中解析 Java 中的 XML

javascript - 从模板字符串中渲染空白

shell - 将带有混合空格/制表符的 txt 文件转换为仅制表符(在可能的情况下)

c# - 从 CSS 代码解析字符串

c# - Dispatcher.CurrentDispatcher.BeginInvoke 未调用

c# - 将 int(或任何值类型)存储为对象并将它们转换回 int(或值类型)是否有任何成本?

c# - 将我的项目中的表单添加到另一个项目

string - 替换字符串列表中的特殊字符和空格