Issue with XDocument and the BOM (Byte Order Mark)

2019-05-03 07:12发布

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

7条回答
等我变得足够好
2楼-- · 2019-05-03 07:41

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-05-03 07:41

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

查看更多
Lonely孤独者°
4楼-- · 2019-05-03 07:44

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

查看更多
看我几分像从前
5楼-- · 2019-05-03 07:52

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); 
查看更多
老娘就宠你
6楼-- · 2019-05-03 07:56

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

查看更多
Root(大扎)
7楼-- · 2019-05-03 07:57

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);
查看更多
登录 后发表回答