Is there any way to output the contents of an XDocument without the BOM? When reading the output with Flash, it causes errors.
问题:
回答1:
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.
回答2:
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);
回答3:
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:
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);
回答5:
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.
回答6:
You could probably use System.Text.Encoding.Convert() on the output; Just as something to try, not something I have tested.
回答7:
Convert it to a string, then remove the mark yourself.