0

I read XML from WCF and I need to save the XML to my disk but I get a BOM character when I save it. I don't want this character included, so I tried different ways to write the document without it, but it is not working, I don't know what is wrong. Any idea?

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(vReply.xmlDocumento);

////-------------------------- Save without BOM  -----------------------

var bytes = Encoding.UTF8.GetBytes(vReply.xmlDocumento);
var stream = new MemoryStream(bytes);

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false); // The false means, do not emit the BOM.
using (XmlWriter w = XmlWriter.Create("c://temp/my.xml", settings))
{
    xmlDoc.Save(w);
}
dbc
  • 104,963
  • 20
  • 228
  • 340
KlingCan
  • 29
  • 5
  • 3
    Possible duplicate of [How can I remove the BOM from XmlTextWriter using C#?](https://stackoverflow.com/questions/1755958/how-can-i-remove-the-bom-from-xmltextwriter-using-c) – Sami Kuhmonen Apr 10 '19 at 03:54
  • wcf is using http so you need to convert any http special character to/from their http values using System.Net.WebUtility.HtmlEncode(string) and System.Net.WebUtility.HtmlDecode(string). See Wiki : https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references – jdweng Apr 10 '19 at 08:59
  • I can't reproduce your problem, see https://dotnetfiddle.net/4VzxJd. The bytes written to the file do not contain a BOM, they correctly start with the bytes `60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34,117,116,102,45,56,34,63,62` which correspond to the XML declaration ``. Notice no BOM is included. Can you please [edit] your question to share a [mcve]? – dbc Apr 10 '19 at 18:49
  • (Of course the bytes in the `MemoryStream stream` might contain a BOM since you did not write them using `UTF8Encoding(false)`. Only the file `"c://temp/my.xml"` should be written without the BOM.) – dbc Apr 10 '19 at 18:50
  • This is the example of code code that i wanto to revove – KlingCan Apr 16 '19 at 21:02
  • This is the example of bom code that i wanto to remove o;? – KlingCan Apr 16 '19 at 21:12
  • @KlingCan that's not a BOM; that's xml preamble; a BOM would be 0xEFBBBF as the first 3 bytes of the file - you want `settings.OmitXmlDeclaration = true;` – Marc Gravell May 22 '19 at 09:07

0 Answers0