13

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);
1
  • FYI, you should not use new XmlTextReader() or new XmlTextWriter(). They have been deprecated since .NET 2.0. Use XmlReader.Create() or XmlWriter.Create() instead. Jun 25, 2014 at 1:17

2 Answers 2

31

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);
}
9
  • Hi Jon, thanks for the quick reply, so are you saying to remove the XmlTextWriter section at the beginning and only use the TextWriter at the end of the method?
    – Chris
    Nov 18, 2009 at 17:06
  • Well it's not clear what your code is meant to be doing. Why are you currently saving the file and then reloading it?
    – Jon Skeet
    Nov 18, 2009 at 18:07
  • Im just trying to create an XML file with a range of different nodes inside it. To be honest i was in a rush and pulled the section from another site and changed it where appropriate.
    – Chris
    Nov 19, 2009 at 8:11
  • @Chris: Okay, in that case yes, you can move the XmlTextWriter part to the bottom - or just use XmlDocument.Save in the way I've shown in the answer.
    – Jon Skeet
    Nov 19, 2009 at 8:18
  • Hi Jon, thanks for your help, i finally managed to get this working.
    – Chris
    Nov 19, 2009 at 10:20
0

I'd write the XML to a string(builder) instead and then write that string to file.

1
  • This approach is slower than necessary and will eat up extra memory if your XML data set is large enough, as you're adding an unnecessary middle step.. Best to write directly to the file using Xml[Text]Writer as indicated by the other answers.
    – user169771
    Mar 31, 2016 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.