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!