0

I've created a C# application to load an existing XML document, made minor changes to a couple of the children nodes, and saved the new XML document using the code below.

 XDocument xdoc = XDocument.Load(originalFilePath);
 // do stuff..
 xdoc.Save(newFilePath);

The changes I make in the document are not at the root level. When I open the new XML file in Notepad++ it all looks as expected. When I compare the new and old XML documents using WinDiff, there seems to be extra characters in front of the first node (see image below).

 <Root Version="5.1.5.1">      <-- Original file
 <Root Version="5.1.5.1">   <-- New file

That extra characters causes the XML document fail to load in another 3rd party application (which I cannot control). Any idea why the hidden characters may be there?

When I use the code below, the xml document saves without any extra characters.

 using (XmlReader xmlReader = xdoc.CreateReader())
 {
      XmlDocument xmlDoc = new XmlDocument();
      xmlDoc.Load(xmlReader);
      xmlDoc.Save(newFilePath);
 }

XML Comparison

Charlie P
  • 51
  • 2
  • 8
  • 3
    Does this answer your question? [XDocument: saving XML to file without BOM](https://stackoverflow.com/questions/4942825/xdocument-saving-xml-to-file-without-bom) – madreflection Jan 10 '20 at 20:33
  • 2
    Those characters are the BOM (Byte Order Marker); those bytes, EF BB BF, indicate that the file is encoded as UTF-8. The other application is *broken* if it can't understand that, but the duplicate I've flagged shows how to exclude it from the output. – madreflection Jan 10 '20 at 20:33
  • Thanks for the feedback. this is extremely helpful! – Charlie P Jan 14 '20 at 04:14

0 Answers0