27

Despite using the SaveOptions.DisableFormatting option in the following code:

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);

the target XML file gets this added to it:

<?xml version="1.0" encoding="utf-8"?>

Is there a way to preserve the original formatting and not have the version and encoding information added?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Ein Doofus
  • 495
  • 1
  • 5
  • 12
  • 4
    That's not formatting. It's part of the document. What problem causes you to want that removed? – John Saunders May 21 '13 at 23:38
  • I'm trying to create synthetic data using existing XML files that omit that portion. Aside from my alterations I'd like the resulting XML files to be as close to the original as possible. – Ein Doofus May 22 '13 at 00:12
  • No code should have a problem with having these directives in place. If any code cares about it, then it is broken and should be fixed ASAP. – John Saunders May 22 '13 at 01:08
  • Infopath Sharepoint integration uses XML files that sometimes require no XML declaration. That's Microsoft code. – Coruscate5 Nov 29 '16 at 21:16

1 Answers1

45

That's the behaviour of the XDocument.Save method when serializing to a file or a TextWriter. If you want to omit the XML declaration, you can either use XmlWriter (as shown below) or call ToString. Refer to Serializing with an XML Declaration.

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);
Douglas
  • 53,759
  • 13
  • 140
  • 188