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?
That's the behaviour of the
XDocument.Save
method when serializing to a file or aTextWriter
. If you want to omit the XML declaration, you can either useXmlWriter
(as shown below) or callToString
. Refer to Serializing with an XML Declaration.