使用 XElement 保存 XML 文件时,文件中的对齐方式也会发生变化,如何避免? [英] When saving XML file with XElement, alignment in file changes as well, how to avoid?

查看:18
本文介绍了使用 XElement 保存 XML 文件时,文件中的对齐方式也会发生变化,如何避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

XElement root = XElement.Load(filepath);

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

to load XML file, then finding things that I need.

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

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

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

When I am done with my changes, I save the file with the following code.

root.Save(filepath);

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

When file is saved, all the lines in my XML file are affected. Visual Studio aligns all the lines by default, but I need to save the original file format.

我不能改变文档的任何部分,除了 Group 属性值.

I cannot alter any part of the document, except the Group attribute values.

command.SetAttributeValue("Group") attributes.

推荐答案

您需要:

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

然后做:

root.Save(filepath, SaveOptions.DisableFormatting);

这将通过使用 保留您的原始空白LoadOptionsSaveOptions.

This will preserve your original whitespace through the use of LoadOptions and SaveOptions.

这篇关于使用 XElement 保存 XML 文件时,文件中的对齐方式也会发生变化,如何避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆