Is there any way to output the contents of an XDocument without the BOM? When reading the output with Flash, it causes errors.
-
possible duplicate of [XDocument: saving XML to file without BOM](http://stackoverflow.com/questions/4942825/xdocument-saving-xml-to-file-without-bom) – Kevin Panko Feb 28 '14 at 19:32
7 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.

- 23,679
- 13
- 59
- 69
-
1Are you sure? I don't get a compile error, and the documentation says it isn't read only: http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.encoding.aspx – Chris Wenham Oct 01 '08 at 19:32
-
-
You could use Chris's method below to write to a MemoryStream instead. – Chris Wenham Oct 01 '08 at 20:04
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);

- 23,679
- 13
- 59
- 69

- 492
- 3
- 6
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

- 4,166
- 2
- 29
- 33
Kind of a combination of postings, maybe something like this:
MemoryStream ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms, new UTF8Encoding(false));
xmlDocument.Save(writer);

- 32,199
- 5
- 49
- 61
As stated, this problem has a bad smell.
According to this support note, Flash uses the BOM to disambiguate between UTF-16BE and UTF-16LE, which is as it should be. So you shouldn't be getting an error from Flash: XDocument produces UTF16 encoded well-formed XML, and Macromedia claims that Flash can read UTF16 encoded well-formed XML.
This makes me suspect that whatever the problem is that you're encountering, it probably isn't being caused by the BOM. If it were me, I'd dig around more, with the expectation that the actual problem is somewhere else.

- 94,622
- 24
- 146
- 218
You could probably use System.Text.Encoding.Convert() on the output; Just as something to try, not something I have tested.

- 32,199
- 5
- 49
- 61