开发者

c# How to load a memory stream to an xmldocument without BOM? (My memory stream is generated from XMLTextWriter without BOM)

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.A开发者_StackOverflow中文版ppendChild(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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜