views:

1015

answers:

2

Hi, i need to remove the BOM from an XML file that is being created. I have tried using the new UTF8Encoding(false) method but it doesnt 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);

Any help would be appreciated, am almost finished on this project and its holding me up. Thanks in advance. Chris

A: 

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

danbystrom
+5  A: 

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, new UTF8Encoding(false))
{
    xmlDoc.Save(writer);
}
Jon Skeet
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
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
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
@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
Hi Jon, thanks for your help, i finally managed to get this working.
Chris