如何防止XDocument添加XML版本和编码信息

尽管在以下代码中使用了SaveOptions.DisableFormatting选项:

XDocument xmlDoc = XDocument.Load(FileManager.SourceFile); string element="campaign"; string attribute="id"; var items = from item in xmlDoc.Descendants(element) select item; foreach (XElement itemAttribute in items) { itemAttribute.SetAttributeValue(attribute, "it worked!"); //itemElement.SetElementValue("name", "Lord of the Rings Figures"); } xmlDoc.Save(TargetFile, SaveOptions.DisableFormatting); 

目标XML文件将其添加到它:

  

有没有办法保留原始格式,并没有添加版本和编码信息?

这是序列化到文件或TextWriterXDocument.Save方法的行为。 如果要省略XML声明,可以使用XmlWriter (如下所示)或调用ToString 。 请参阅使用XML声明进行序列化 。

 XDocument xmlDoc = XDocument.Load(FileManager.SourceFile); // perform your modifications on xmlDoc here XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true }; using (XmlWriter xw = XmlWriter.Create(targetFile, xws)) xmlDoc.Save(xw);