简体   繁体   English

如何使用C#从XmlTextWriter中删除BOM?

[英]How can I remove the BOM from XmlTextWriter using C#?

How do remove the BOM from an XML file that is being created? 如何从正在创建的XML文件中删除BOM?

I have tried using the new UTF8Encoding(false) method, but it doesn't work. 我尝试过使用新的UTF8Encoding(false)方法,但它不起作用。 Here is the code I have: 这是我的代码:

XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(filename, new UTF8Encoding(false));
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("items");
xmlWriter.Close();
xmlDoc.Load(filename);
XmlNode root = xmlDoc.DocumentElement;
XmlElement item = xmlDoc.CreateElement("item");
root.AppendChild(item);
XmlElement itemCategory = xmlDoc.CreateElement("category");
XmlText itemCategoryText = xmlDoc.CreateTextNode("test");
item.AppendChild(itemCategory);
itemCategory.AppendChild(itemCategoryText);
xmlDoc.Save(filename);

You're saving the file twice - once with XmlTextWriter and once with xmlDoc.Save . 您将文件保存两次 - 一次使用XmlTextWriter ,一次使用xmlDoc.Save Saving from the XmlTextWriter isn't adding a BOM - saving with xmlDoc.Save is. XmlTextWriter保存添加BOM - 使用xmlDoc.Save保存。

Just save to a TextWriter instead, so that you can specify the encoding again: 只需保存到TextWriter ,以便您可以再次指定编码:

using (TextWriter writer = new StreamWriter(filename, false,
                                            new UTF8Encoding(false))
{
    xmlDoc.Save(writer);
}

我将XML写入字符串(构建器),然后将该字符串写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM