views:

781

answers:

7

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

A: 

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

Chris Shaffer
A: 

Convert it to a string, then remove the mark yourself.

Chris Lively
+3  A: 

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.

C. Lawrence Wenham
writer.Settings.Encoding is read only
John Sheehan
Are 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
C. Lawrence Wenham
how do I get from here to a string?
John Sheehan
You could use Chris's method below to write to a MemoryStream instead.
C. Lawrence Wenham
+2  A: 

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);
Chris Shaffer
+1  A: 

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.

Robert Rossney
+1  A: 

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

MattH
+1  A: 

Slight mod to Chris Welman'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); 
Large Jaguar