Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用C#从XmlTextWriter中删除BOM?_C#_Xml_Byte Order Mark_Xmlwriter - Fatal编程技术网

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

如何使用C#从XmlTextWriter中删除BOM?,c#,xml,byte-order-mark,xmlwriter,C#,Xml,Byte Order Mark,Xmlwriter,如何从正在创建的XML文件中删除BOM表 我尝试过使用新的UTF8Encoding(false)方法,但它不起作用。以下是我的代码: XmlDocument xmlDoc = new XmlDocument(); XmlTextWriter xmlWriter = new XmlTextWriter(filename, new UTF8Encoding(false)); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProc

如何从正在创建的XML文件中删除BOM表

我尝试过使用新的UTF8Encoding(false)方法,但它不起作用。以下是我的代码:

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);

我会将XML写入一个字符串(生成器),然后将该字符串写入文件。

您将保存文件两次—一次使用
XmlTextWriter
,一次使用
xmlDoc.Save
。从
XmlTextWriter
保存不是添加BOM,而是使用
xmlDoc.Save
保存

只需保存到
TextWriter
,即可再次指定编码:

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

嗨,Jon,谢谢你的快速回复,那么你是说在开始时删除XmlTextWriter部分,只在方法的结尾使用TextWriter吗?现在还不清楚你的代码要做什么。为什么你现在要保存文件然后重新加载?我只是想创建一个包含一系列不同节点的XML文件。老实说,我当时很忙,从另一个网站上删除了该部分,并在适当的地方对其进行了更改。@Chris:好的,在这种情况下,是的,您可以将XmlTextWriter部分移到底部,或者只使用
XmlDocument。按照我在回答中显示的方式保存。
。嗨,Jon,谢谢您的帮助,我终于成功了。仅供参考,您不应该使用
new XmlTextReader()
new XmlTextWriter()
。自.NET 2.0以来,它们一直被弃用。改用
XmlReader.Create()
XmlWriter.Create()
。这种方法比必要的速度慢,如果XML数据集足够大,就会消耗额外的内存,因为您要添加不必要的中间步骤。。如其他答案所示,最好使用Xml[Text]Writer直接写入文件。