Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用XDocument保留所有XML格式?_C#_Xml_Linq To Xml - Fatal编程技术网

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

C# 如何使用XDocument保留所有XML格式?,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我试图读入一个XML配置文件,做一些调整(查找、删除或添加一个元素),然后再次保存它。我希望此编辑尽可能非侵入性,因为文件将受源代码管理,我不希望不重要的更改导致合并冲突等。这大致就是我得到的: XDocument configDoc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); // modifications to configDoc here configDoc.Save(fileName, SaveOptions.

我试图读入一个XML配置文件,做一些调整(查找、删除或添加一个元素),然后再次保存它。我希望此编辑尽可能非侵入性,因为文件将受源代码管理,我不希望不重要的更改导致合并冲突等。这大致就是我得到的:

XDocument configDoc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
// modifications to configDoc here
configDoc.Save(fileName, SaveOptions.DisableFormatting);
这里出现了一些问题:

  • encoding=“utf-8”
    被添加到xml声明中
  • 更改为
  • 为了可读性而分散在不同行上的属性被全部推到一行上

  • 有没有办法减少对XDocument的干扰,或者我只需尝试进行字符串编辑就可以得到我想要的内容?

    LINQ to XML对象模型不存储解析的元素是否标记为
    ,因此在保存此类信息时会丢失。如果您希望确保某种格式,那么可以扩展XmlWriter实现并重写它,但这样您也不会保留输入格式,而是将任何空元素写成
    或在方法中实现的任何格式

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

    <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>
    
    
    例子
    例子
    
    把它存回去结果是

    <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>
    
    
    例子
    例子
    

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

    为了避免文档标题中的声明,可以使用以下方法

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
    
    
            using (XmlWriter xw = XmlWriter.Create(fileName, settings))
            {
                doc.Save(xw);
            }
    

    所以我猜简单的答案是“你不能”(