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

时间:2013-04-22 19:50:31

标签: 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会对齐所有行,但我需要保存原始文件格式。

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

command.SetAttributeValue("Group") attributes.

2 个答案:

答案 0 :(得分:11)

您需要这样做:

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

然后做:

root.Save(filepath, SaveOptions.DisableFormatting);

这将通过LoadOptionsSaveOptions保留原始空白。

答案 1 :(得分:1)

您希望保留的信息在XDocument中开始丢失。

XDocument不关心你的元素在它们前面的行上是否有标签或空格,以及属性之间是否有多个空格等。如果你想依赖Save()方法,你必须放弃这个想法你可以保留格式。

要保留格式,您需要添加自定义处理并找出准确更改的位置。或者,如果您的XML来自计算机而非人工编辑,您可以调整保存选项以匹配您的格式

相关问题