如何使用XDocument保留所有XML格式?

Ran*_*ngy 8 c# xml linq-to-xml

我正在尝试读取XML配置文件,进行一些调整(查找和删除或添加元素)并再次保存.我希望这个编辑尽可能不侵入,因为该文件将受源代码控制,我不希望无关紧要的更改导致合并冲突等.这大致是我得到的:

XDocument configDoc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
// modifications to configDoc here
configDoc.Save(fileName, SaveOptions.DisableFormatting);
Run Code Online (Sandbox Code Playgroud)

这里出现了一些问题:

  1. encoding="utf-8" 被添加到xml声明中.
  2. <tag attr="val"/> 变了 <tag attr="val" />
  3. 为了便于阅读而分散在不同行中的属性将全部推送到一行.

是否有任何方法可以减少对XDocument的干扰,或者我是否必须尝试进行字符串编辑以获得我想要的内容?

Mar*_*nen 5

在LINQ到XML对象模型不存储解析元素是否被标记为<foo/><foo />使保存回这样的信息时,会丢失.如果你想确保某种格式,那么你可以扩展一个XmlWriter实现并覆盖它的http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.writeendelement.aspx,但那样你也不会保留输入格式,然后你会写出任何空元素<foo/>或你在方法中实现的任何格式.

还可能发生其他更改,例如加载文件时

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <head>
    <title>Example</title>
  </head>
  <body>
    <h1>Example</h1>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

并将结果保存回来

<xhtml:html xmlns="http://www.w3.org/1999/xhtml" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <xhtml:head>
    <xhtml:title>Example</xhtml:title>
  </xhtml:head>
  <xhtml:body>
    <xhtml:h1>Example</xhtml:h1>
  </xhtml:body>
</xhtml:html>
Run Code Online (Sandbox Code Playgroud)

因此,在使用XDocument/XElement加载/保存时,不要指望保留标记详细信息.

  • 所以我想简短的回答是“你不能”。:( (3认同)