1

My problem is really strange.I need to write a huge xml file from different sources in c#.

So first to begin with,I use XmlTextWriter to write to a memory stream:

     MemoryStream ms=new MemoryStream();
     XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        **settings.Encoding = new UTF8Encoding(false,false); // set UTF8 without BOM !!**
        XmlWriter xmlWriter = XmlWriter.Create(ms, settings);
        xmlWriter.WriteStartDocument();

        xmlWriter.WriteStartElement();

        xmlWriter.WriteEndElement(); 
        xmlWriter.WriteEndDocument()

        xmlWriter.Flush();

        xmlWriter.Close();

Note that ms will not be closed after closing xmlTextWriter. So I pass ms to a xmlDocument and write other parts of xml elements:

        XmlDocument doc = new XmlDocument();
        ms.Position=0;
        doc.Load(ms);

Then I write by using:

       XmlElement elmRoot=doc.DocumentElement(); //root
       XmlElement elm=doc.CreateElement("New Element");
       XmlAttribute att=doc.CreateAttribute("att");
       att.Value="ABC";
       elm.Attributes.Append(att);
       elmRoot.AppendChild(elm);
       ms.Position=0;
       doc.Save(ms)

However, after the above operations, I found that ms still has three BOM at the beginning of generated xml file, causing the file cannot be opened in a browser. Any ideas?

Thanks a lot!

Summer
  • 161
  • 1
  • 7
  • 13
  • Have no idea but found this: http://stackoverflow.com/questions/1755958/how-can-i-remove-bom-from-xmltextwriter-using-c/1755993#1755993 – Torbjörn Hansson May 25 '11 at 15:57
  • Thanks Torbjorn. I know the problem is doc.save(ms) which will add BOM. The solution in the link you posted is to use doc.save(xmlwriter) and set encoding(false) in xmlwriter. However, is it possible to omit BOM in doc.save(ms)? Otherwise, I may need to re-write a lot of codes.... – Summer May 25 '11 at 16:53

1 Answers1

1

I don't know why you're overwriting the MemoryStream again, that seems a bad idea.

But if you need the XDocument then you can use the XDocument.Save(XmlWriter writer) option and make sure you create the writer with the no-BOM settings as in the beginning of your code.

H H
  • 263,252
  • 30
  • 330
  • 514