如何使用 XDocument 保留所有 XML 格式?
我正在尝试读取 XML 配置文件,进行一些调整(查找并删除或添加元素)并再次保存它。我希望此编辑尽可能不具有侵入性,因为文件将受到源代码控制,并且我不希望无关紧要的更改导致合并冲突等。这大致就是我遇到的问题
XDocument configDoc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
// modifications to configDoc here
configDoc.Save(fileName, SaveOptions.DisableFormatting);
:此处:
encoding="utf-8"
添加到 xml 声明中。
更改为- 为了便于阅读而分布在不同行上的属性被推送全部集中在一条线上。
有什么方法可以减少对 XDocument 的干扰,还是我必须尝试进行字符串编辑才能获得我想要的内容?
I'm trying to read in an XML configuration file, do a few tweaks (finding and removing or adding an element) and save it again. I want this edit to be as non-intrusive as possible since the file will be under source control and I don't want inconsequential changes to cause merge conflicts, etc. This is roughly what I've got:
XDocument configDoc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
// modifications to configDoc here
configDoc.Save(fileName, SaveOptions.DisableFormatting);
There's a few problems that pop up here:
encoding="utf-8"
gets added to the xml declaration.<tag attr="val"/>
gets changed to<tag attr="val" />
- Attributes that were spread across separate lines for readability get pushed all on to one line.
Is there any way to be less intrusive with XDocument or will I have to just try and do string editing to get what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
LINQ to XML 对象模型不存储解析的元素是否标记为
还是
,因此在保存此类信息时丢失了。如果您想确保某种格式,那么您可以扩展 XmlWriter 实现并覆盖其 http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.writeendelement.aspx 但这样你也不会保留输入格式,而是你会写出所有空元素作为
或您在方法中实现的任何格式。还可能发生其他更改,例如加载文件
并将其保存回结果时,
因此不要期望在使用 XDocument/XElement 加载/保存时保留标记详细信息。
The LINQ to XML object model does not store whether an element parsed is marked up as
<foo/>
or<foo />
so when saving back such information is lost. If you want to ensure a certain format then you could extend an XmlWriter implementation and override its http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.writeendelement.aspx but that way you would also not preserve the input format, rather you would then write out any empty elements as<foo/>
or whatever format you implement in your method.There are other changes that can happen, for instance when loading the file
and saving it back the result is
so don't expect markup details to be preserved when loading/saving with XDocument/XElement.
为了避免在文档标题中声明,您可以使用以下内容
To avoid the declaration in the header of the document you can use the following