How can I remove the BOM from XmlTextWriter using C#?
Asked Answered
S

1

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);
Sal answered 18/11, 2009 at 13:27 Comment(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.Strati
S
32

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);
}
Stotinka answered 18/11, 2009 at 13:34 Comment(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?Sal
Well it's not clear what your code is meant to be doing. Why are you currently saving the file and then reloading it?Stotinka
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.Sal
@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.Stotinka
Hi Jon, thanks for your help, i finally managed to get this working.Sal
I'm not sure why but this does not work for me the second parameter of StreamWriter must be a bool.Bickart
@rekire: Well you haven't told us anything about your context, which makes it hard to help you. What sort of app are you writing?Stotinka
@JonSkeet I'm implementing a console project (targeting .net 4.5). I Could fix this problem by using this constructor: new StreamWriter(outfile, false, new UTF8Encoding(false)). It's just wired that a constructor seems to been removed.Bickart
@rekire: I think it was my mistake, actually - it looks like there's a stream version with just an encoding, but not a string version. Will edit the answer.Stotinka

© 2022 - 2024 — McMap. All rights reserved.