如何从XmlTextWriter的使​​用C#删除BOM? [英] How can I remove the BOM from XmlTextWriter using C#?

查看:211
本文介绍了如何从XmlTextWriter的使​​用C#删除BOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从正在创建一个XML文件中删除BOM?

我已使用新的UTF8Encoding(假)方法试过,但它不工作。这里是code我有:

 的XmlDocument xmlDoc中=新的XmlDocument();
XmlTextWriter的的XmlWriter =新的XmlTextWriter(文件名,新UTF8Encoding(假));
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction(XML,版本='1.0'编码='UTF-8');
xmlWriter.WriteStartElement(项目);
xmlWriter.Close();
xmlDoc.Load(文件名);
XmlNode的根= xmlDoc.DocumentElement;
XmlElement的项目= xmlDoc.CreateElement(项目);
root.AppendChild(项目);
的XmlElement itemCategory = xmlDoc.CreateElement(类);
XMLTEXT itemCategoryText = xmlDoc.CreateTextNode(测试);
item.AppendChild(itemCategory);
itemCategory.AppendChild(itemCategoryText);
xmlDoc.Save(文件名);


解决方案

您正在保存文件两次 - 以的XmlTextWriter 键和一次xmlDoc.Save 。与 xmlDoc.Save 节能是 - 从的XmlTextWriter 的加入BOM节约

只是保存到的TextWriter 来代替,这样就可以重新指定编码:

 使用(TextWriter的作家=新的StreamWriter(文件名,假的,
                                            新的UTF8Encoding(假))
{
    xmlDoc.Save(作家);
}

How do remove the BOM from an XML file that is being created?

I have tried using the new UTF8Encoding(false) method, but it doesn't work. 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. Saving from the XmlTextWriter isn't adding a BOM - saving with xmlDoc.Save is.

Just save to a TextWriter instead, so that you can specify the encoding again:

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

这篇关于如何从XmlTextWriter的使​​用C#删除BOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆