Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with XDocument and the BOM (Byte Order Mark)

Is there any way to output the contents of an XDocument without the BOM? When reading the output with Flash, it causes errors.

like image 256
John Sheehan Avatar asked Oct 01 '08 18:10

John Sheehan


3 Answers

If you're writing the XML with an XmlWriter, you can set the Encoding to one that has been initialized to leave out the BOM.

EG: System.Text.UTF8Encoding's constructor takes a boolean to specify whether you want the BOM, so:

XmlWriter writer = XmlWriter.Create("foo.xml");
writer.Settings.Encoding = new System.Text.UTF8Encoding(false);
myXDocument.WriteTo(writer);

Would create an XmlWriter with UTF-8 encoding and without the Byte Order Mark.

like image 101
Chris Wenham Avatar answered Nov 15 '22 04:11

Chris Wenham


Slight mod to Chris Wenham's answer.

You can't modify the encoding once the XmlWriter is created, but you can set it using the XmlWriterSettings when creating the XmlWriter

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new System.Text.UTF8Encoding(false); 

XmlWriter writer = XmlWriter.Create("foo.xml", settings); 
myXDocument.WriteTo(writer); 
like image 31
Reed Rector Avatar answered Nov 15 '22 06:11

Reed Rector


I couldn't add a comment above, but if anyone uses Chris Wenham's suggestion, remember to Dispose of the writer! I spent some time wondering why my output was truncated, and that was the reason.

Suggest a using(XmlWriter...) {...} change to Chris' suggestion

like image 43
MattH Avatar answered Nov 15 '22 05:11

MattH