Link to home
Start Free TrialLog in
Avatar of jetbet
jetbetFlag for New Zealand

asked on

C# XDocument.Save adds unwanted encoding information

I have a set of XML files that I load into XDocuments, adjust some data and save.
The original document has the following as the first line
<?xml version="1.0"?>
once saved this becomes
<?xml version="1.0" encoding="UTF-8"?>

I then SFTP these files to another application that parses them. Unfortunately this now causes a XML -1072896682 error.

I used to do this conversion via a perl script using  XML::LibXML which gave me no issues.

Does anyone know how I can save the XDocument without adding this extra information.
var doc = XDocument.Load(file);
                            var q1 = from c in doc.Elements("meeting")
                                     select c;

                            foreach (XElement date in q1)
                            {
                                date.Attribute("meetingdate").Value = meetingDate;
                            }

                            var q2 = from c in doc.Elements("meeting").Elements("races").Elements("race")
                                     select c;
                            foreach (XElement date in q2)
                            {
                                date.Attribute("racedate").Value = meetingDate;
                            }
                            doc.Save(Path.Combine(ver4Directory, "Ver4_" + fileNameDate + "_" + key));

Open in new window

Avatar of jetbet
jetbet
Flag of New Zealand image

ASKER

Actual output produced by other application is

03/10 09:24:28.765 *** Exception 7: Exception Error -1072896682 Invalid at the top level of the document.
 in "<?xml version="1.0" encoding="utf-8"?>" at line 1, column 1

This file opens correctly in IE and shows as valid XML in editors
ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Most editors do understand how to deal with the BOM, that is why you don't see the issue in IE or in editors
Avatar of jetbet

ASKER

Changed the same to the following call (as the link recommended) at it works like a charm.

Thanks,

using (var writer = new XmlTextWriter(Path.Combine(ver4Directory, "Ver4_" + fileNameDate + "_" + key), new UTF8Encoding(false)))
   {
     doc.Save(writer);
       }